BACK
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:

  1. For each incoming value, it calls projectFn and gets an inner Observable.
  2. 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 mergeMap to.
  • Inner stream — the one projectFn returned for a specific value.

Your task

  1. In pipe, add mergeMap(value => timer(value * 20).pipe(map(() => 'Done ' + value))).
  2. The source emits 3, 1, 2 — each spawns a timer of its own length.
  3. Since 1 is shorter than 3, the result Done 1 arrives before Done 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 // TypeScript
CONSOLE · Console output
Hit Run to see the result...