Demo:  mergeMap

mergeMap => map + mergeAll the mapped observables

The mergeMap is useful in mapping the incoming values to tasks and executing them immediately as they arrive, allowing to run tasks in parallel.

  1. To start with, the map part maps each incoming value to an observable, representing our intended task, and puts them for execution by mergeAll.
  2. Then mergeAll, executes each task immediately as it arrives, allowing the tasks to run in parallel.

Thus, the output of the tasks here, may not follow their incoming order as in concatMap, but, the execution time will be much faster.

const source = timer(500,2500).pipe(take(3));

//1. Each input from source maps to this counting task
const countTill3Task = timer(0,1000).pipe(take(4));

//2. mergeMap starts executing countTill3Task immediately as it arrives
const mapAndMerge = mergeMap(v => countTill3Task);

const output = source.pipe(mapAndMerge).subscribe(v=>console.log(v))
What is happening ?

The merge Map is a combination of the map and the "merge All" operator.

  • To start with, the map part maps our input to an observable that specifies our intended task.
  • And, puts that into a stream for execution by merge All.
  • Then merge All, executes each task immediately as it arrives, allowing the tasks to run in parallel.

Coming to our demo on merge Map:

  • We are mapping each of our input to a count till 3 task and submitting it for execution.
  • On the execution part, as we can see, each count till 3 task starts immediately as it arrives.
  • It leads to multiple count tasks running in parallel, their output overlapping on each other.

If we compare it with the concat Map:

  • The output here may be overlapping on each other and may not follow their incoming order as in concat Map.
  • But, the execution time will be much faster.