RxJS Functions (Part 3)

Corey Pyle
3 min readJan 10, 2019

--

combineLatest

Traditionally, marble diagrams have been used to illustrate how RxJS functions work. Some have even come up with clever tools for this purpose. I quite like this one, though it seems to be out of date. Personally, though, these diagrams never really clicked with me.

As this is the first function I’m going over that actually manipulates the data stream of multiple Observables, I took some time to make a StackBlitz that visualizes the event emissions in a way that makes more sense to me. If it helps you too, I’d love to hear about it.

combineLatest

Combines multiple Observables to create an Observable whose values are calculated from the latest values of each of its input Observables.

Note: there are two ‘combineLatest’ functions. One is this one, the other is the deprecated operator version which I will not cover.

A common use case for combineLatest would be when you have two disparate sources that are used in conjunction throughout your app. For example, let’s say your first source is a catalog of movies, and your second source is a user with a property containing the IDs of favorited movies:

The above example sets up some initial data for movies and the user, creates a BehaviorSubject initialized with that data, and subscribes. Upon running, the array of movies and the user object are logged to the console.

Your app needs both the movie data and the user data in order to display favorited movies in various places. You need to make sure that every time the array of movies or list of user favorites is updated that data is combined properly and propagated throughout the app. combineLatest (in conjunction with a couple of other operators) can help you there:

Now every time movies$ or user$ is updated, our Observable created with combineLatest will output the user’s favorite movies!

There’s two additional things I’d like to call out.

First, I’m using map here because combineLatest doesn’t do any magic to merge the data; it just outputs an array of every value each time one of the source observables emits.

Second, the example above will emit every time movies$ or user$ is updated. This may not be desirable. Instead you may want to filter the observables and check only for emissions where the user’s favorite movies were affected.

Thanks for reading. Stay tuned for Part 4, and be sure to check out the previous articles in this series as well.

--

--