...

/

The Declarative Pattern for Filtering Data

The Declarative Pattern for Filtering Data

Explore the concept of the declarative pattern to filter data.

Multiple streams

We need to think of everything as a stream. This is the golden rule.

We have recipes$, which is our data stream. What if we were to consider the click on the “See Results” button as a stream as well? We don’t know when, but every time the user clicks “See Results,” the action stream emits the value of the filter.

In total, we have the data stream (responsible for getting the data) and the action stream (responsible for emitting the latest value of the filter). Both of the streams rely on each other; when recipes$ emits a new value, the filter should stay active, and when the filter emits a new value, the recipe list should be updated accordingly.

What we’re really trying to do is get information from different streams. And whenever we want to join information from multiple observables, we should think of one of the combination operators available in RxJS.

Instead of getting the data we need from both streams individually, we can combine them to form a single new stream. And when we have streams that rely on each other, and particularly on the latest value emitted by each, we should think of the combineLatest operator.

The combineLatest operator

The combineLatest operator will combine the latest values emitted by the input observables. So every time one of the observables emits, combineLatest will emit the last emitted value from each. Does that make sense? If not, don’t worry—we’ll detail it further by using a marble diagram, as usual.

Press + to interact
canvasAnimation-image
1 / 6

Let’s break this down:

  • The first line in the marble diagram represents the timeline of the first input observable.
  • The second line represents the timeline of the second input observable. So combineLatest has two inputs.
  • The last line represents the timeline of the output observable returned from the combineLatest operator.

Now let’s dig deep into the execution. The first observable emitted is the value aa ...