Thursday, January 31, 2019

RxJs mergeMap, switchMap, concatMap, exhaustMap in exmples PART 1

We once talked about how mergeMap(flatMap), switchMap, concatMap work and what's those differences between them, in words, without examples. And we missed the youngest kid in the Map family, exhaustMap. It's time to use some example codes to clarify them once for all.



In order to illustrate the differences, we made a simple scenario about me working on some tasks.

  • There are 5 tasks which I have to do on almost every morning
  • The 5 tasks start in a specific order, which won't change at all.
  • But how long each task takes to finish it, that's indeterminate, random.
  • Our mappers wait for a task finish and emit message to info the finish.
There is the online example of this scenario.

The code to generate my 5 tasks

The code to work on tasks, notice that we set the work time as random, from 0 ~ 2 seconds.


mergeMap

mergeMap treat every received item independently, or you can say, as parallel. It does not care the order, each time on receiving an item it just pass the item through.

The code here...

The result

You can see tasks finish in random orders, that's because we make the working time like so, mergeMap don't care order, remember? It follows up just as demand, whenever a task is done, that's all.

concatMap

concatMap keeps the order, like bank counters. When you enter the bank usually you get a ticket with some number on it, you'll have to wait until your number get called. No matter how long it takes to serve your shits, just wait until others get their requests done because they arrive first.

The code here

The result

Contrary to mergeMap, here we can see the Finish message strictly follows the Start message of each task. Remember that the work time of each task is still random, so even if task 3 finishes earlier than task 2 does, it still wait until task 2 claims its finish.


No comments:

Post a Comment