RxJS Functions (Part 15)

merge

I broke my streak 😢. But 14 days in a row isn’t too bad I guess. Project work caught up to me. On to an interesting function though!

merge

https://rxjs.dev/api/index/function/merge

Creates an output Observable which concurrently emits all values from every given input Observable.

TL;DR

Create one Observable from multiple Observables. The created Observable emits a value every time one of the merged Observables would emit a value.

Use Case

Whenever you have multiple Observables you want to combine, but you don’t care about the order, it would be a good time to use merge. Let’s take an example of a fictional social media site Instacat. Instacat lets you follow cat owners and every time a cat owner adds a picture, the picture shows up on your feed. Since we just want to see live updates of cat photos in the feed, we can use merge for this.

What’s going on?

We’ve got two Observables: cats$ and dogs$ (ugh, some dog lover is cluttering up our cat feed). All these two Observables do is emit the same two urls at varying intervals. We use merge to combine the cats and dogs. Any time a cat or dog interval ticks, a picture will be added to the feed.


Thanks for reading. Stay tuned for Part 16, and be sure to check out my previous articles.