Demo: concatMap
concatMap => map + concatAll the outputs of the mapped observables
The concatMap is useful in mapping the source items to tasks and executing them strictly in sequence; completing each task before starting the next.
- To start with, the map part maps each incoming value to an observable, representing our intended task, and puts them for execution by concatAll.
- Then concatAll, runs the incoming tasks strictly in sequence, completing each one before starting the next.
A close complementary to concatMap is the mergeMap which runs the mapped tasks in parallel.
const source = timer(500,2500).pipe(take(3));
//1. Each input from source maps to this counting task
const countTill3Task = timer(300,1000).pipe(take(4));
//2. concatMap ensures each countTill3Task runs strictly in sequence
const mapAndConcat = concatMap(v => countTill3Task );
const output = source.pipe(mapAndConcat).subscribe(v=>console.log(v))
What is happening ?
The concatMap is a combination of the map and the concatAll 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 concatAll.
- Then concatAll, runs the incoming tasks strictly in sequence, completing each one before starting the next.
Coming to our demo on concatMap:
- 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 only after it's previous is complete. Moreover, because each tasks run strictly one after the other in order, their output looks concatinated.