Demo:  mergeMapTo

The mergeMapTo is useful in creating a task for each source item and execute them immediately as they arrive, allowing to run them in parallel.

mergerMapTo uses mapTo instead of map operator, hence, it can only map to an observable(or the task) which is independent of the input value.

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. mergeMapTo starts executing countTill3Task immediately as it arrives
const mapToAndMerge = mergeMapTo(countTill3Task);

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

mergeMapTo is the same as mergeMap, the only difference being on the mapping part.

mergeMapTo uses mapTo instead of map operator, hence, it can only map to an observable or the task which is independent of the input value.

Coming to our demo on mergeMapTo, we mapping to the same task as in mergeMap demo:

  • As long as the mapped task is independent of the input value, both the operators are the same.
  • 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.