A quick note on ReactiveX’s Observable.mergeMap()

A quick note on ReactiveX’s Observable.mergeMap()
november 30, 2017 Tobias Ljungström

When working with ReactiveX and Observables there is a handy function called mergeMap (flatMap is an alias in RxJS) that takes an observable of observables of items and flattens them out into a single observable of all the items. This is the use case that is most widely presented in examples around the web when you search for this function, and probably the most powerful application of it. Imagine, for instance, that you have an observable that emits a sequence of ids. Then, using the map-function you map each id to a http call, using the id in the url. Each http call returns an observable of the response, and now you find yourself with an observable of observables of responses. Not entirely practical, so instead of using map you use flatMap, and voila! You now have an observable of responses that each correspond to what was previously an id.

Observable.of(42, 69, 1337)
  .flatMap(id => http.get(id))

There is another use case where mergeMap works just as well however, and that is if you have an observable of an array and you’d rather have an observable of all the items inside the array (so you can filter them or map them or whatever, before the subscription). Use it by applying the function to your observable and mapping each inner item to itself, and you go from an observable of an array of numbers to an observable of numbers.

Observable.of([1, 2, 3])
  .flatMap(item => item)

Ka-ching! ?

0 Kommentarer

Lämna ett svar

E-postadressen publiceras inte. Obligatoriska fält är märkta *


Denna webbplats använder Akismet för att minska skräppost. Lär dig hur din kommentardata bearbetas.