Lessons23. mergeMap: parallel tasks
Lessons · 23
23. mergeMap: parallel tasks
mergeMap — parallel, no ordering
The first of the four flattening operators. mergeMap(projectFn) does two things:
- For each incoming value, it calls
projectFnand gets an inner Observable. - It subscribes to that inner Observable right away and passes its values out.
The key point: the outer stream doesn't wait. When a new value arrives, another inner Observable starts, and both run in parallel.
When to pick mergeMap
- The tasks are independent — order doesn't matter.
- Uploading files in parallel, or independent saves.
- You need all the results, not "the last one wins."
The main characteristic
The order of results is not preserved. If the first task takes longer than the second, the second result arrives first.
Glossary
- Outer stream — the one you attached
mergeMapto. - Inner stream — the one
projectFnreturned for a specific value.
Your task
- In
pipe, addmergeMap(value => timer(value * 20).pipe(map(() => 'Done ' + value))). - The source emits
3, 1, 2— each spawns a timer of its own length. - Since
1is shorter than3, the resultDone 1arrives beforeDone 3. That's "no ordering preserved."
Deterministic check
This task's check runs in TestScheduler virtual time. If your solution is right, the console shows only Test Passed!. Don't add extra console.logs, or the check will fail.
Solution spoiler · click to reveal
const { of, timer, mergeMap, map } = Rx;
const source$ = of(3, 1, 2);
const result$ = source$.pipe(
mergeMap(value => {
return timer(value * 20).pipe(
map(() => 'Done ' + value)
);
})
); script.ts
CONSOLE · Console output
Hit Run to see the result...