Table of contents
Why there are various RxJs maps? What are they used for? What are the differences? Why can't I just use switchMap all the way? This was my thoughts before my friend, Anthony Miller enlightened me.
For an Angular developer that uses NgRx, we often get this dilemma of which type of map should we use upon receiving NgRx action
for our effect
. This issue also happens in any services or functions that rely on observable value change. I'm going to explain and give a small code sample to show you what is the difference of each.
Switch Map
switchMap
is probably something that you see very often in a lot of code samples. It has a unique behaviour of switching from one to another as the name explains.
Theoretically speaking, what it does is: when a next value pushed to the observable, it will cancel previous observable and take the current one instead.
Merge Map
mergeMap
also lives up to its name. Its behaviour allows multiple observable values to be merged and each will run concurrently. Sometimes this behaviour is needed but proceeds very carefully with mergeMap
. In many times, mergeMap
causes race conditions. Use this map only if you know the incoming data will not override each other.
Exhaust Map
When I first hear the word exhaustMap
, I don't understand what is the concept of the naming. Then my friend explained it and it blew my mind! exhaustMap
will prevent any data from going through if the previous observable is not yet completed. This means, whatever data you force into that observable will just get dropped. Not even queued.
Concat Map
At this stage, you might think, so there is no queueing system with observable data? At ease crowd, concatMap
comes to the rescue. As the name explains, concatMap
will append observable data from one to another. It will create a queue that will run when the previous data has been completed.
I have created a repository on GitHub for these various map samples. It may not be the best looking, but it works. If you have any suggestions to make it look nicer and easier to visualise, please don't hesitate to give me feedback.