Search code examples
rxjsreactive-extensions-js

Filter an observable using values from another observable


I have two observables:

  1. An observable representing a list of checkbox inputs.
  2. An observable representing a stream of events coming from the server.

I'd like to filter the second observable using values from the first one.

The values received from the server include a tag property, which corresponds to values in the checkbox list. The observable resulted from the combination of the above two would only yield values from the server whose tag property is included in the set of ticked checkboxes.


Solution

  • You can use withLatestFrom. enter image description here.

    source.withLatestFrom(checkboxes, (data, checkbox) => ({data, checkbox}))
      .filter(({data, checkbox}) => ...)
    

    Here, checkboxes is an observable representing a list of checkbox inputs. source is an observable representing a stream of events coming from the server. In the filter function you can check if the data is valid compared to the checkbox settings and let it trough.

    Notice it is important checkboxes emits at least 1 value before the stream can emit anything.

    Ps. In regard to other answers, this solution works even if the source is cold.