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 is my thoughts before my friend, Anthony Miller enlightens 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 any functions that are relying on observable value change. I'm going to explain and give a small code sample to show you what is the difference of each.
switchMap is probably something that you see very often in a lot of code sample. 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.
mergeMap also lives up to its name. Its behaviour allows multiple observable values to be merged and all to be ran at the concurrently. Sometimes this behaviour is needed but proceeds very carefully with
mergeMap. In many times,
mergeMap causes race condition. Use this map only if you know that your incoming data will not override each other.
When I first hear the word
exhaustMap, I don't actually 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. Which means, whatever data you force into that observable will not even be received. It will be ignored.
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 looks nicer and easier to visualise, please don't hesitate to give me feedback.