loading...
Cover image for Understand RxJs mergeMap operator, Today!

Understand RxJs mergeMap operator, Today!

danmt profile image Daniel Marin ・1 min read

RxJs is a Javascript implementation of Rx, which is a set of Reactive Programming Extensions. If you are doing Angular today, you have to deal with this on a daily basis. Core features like the Router, the Forms, and much more is heavily based on RxJs and it's Observable implementation.

An operator is simply a function that takes an observable, returns another that it automatically subscribes to and its values get emitted in the original observable stream. There's an special kind of operator, that's commonly known as flattening operators.

If the value emitted by the observable is another observable, and you want to handle the inner observable emission as an emission of the outer observable you are gonna need this special kind of operator.

There are 4 flattening operators in RxJs, in this article I'm gonna focus on mergeMap. So, how does it work?

Case of study

Imagine you have an observable A that get's called every second and its emission gets mapped to another observable B that takes 5 seconds to complete.

Result

If you use mergeMap operator, every second a new instance of observable B will be returned an subscribed to and all these instances will run independently of each other. I like to think they go in parallel.

Visual representation of mergeMap running

Conclusion

I hope this helps you understanding what mergeMap can do for you. I mainly use it when I want to do multiple asynchronous calls that are independent of each other, this way you can reduce the total time spent to the one that lasts longer.

Posted on by:

danmt profile

Daniel Marin

@danmt

Passionate about autonomous operations

Discussion

pic
Editor guide