BACK
Lessons24. concatMap: a task queue
Lessons · 24

24. concatMap: a task queue

concatMap — a strict queue

concatMap is a sibling of mergeMap, but with one important difference: it keeps a queue. The next inner Observable starts only after the previous one has fully completed.

inputs: 3 → 1 → 2
mergeMap:  all three run in parallel
concatMap: first the whole task for 3, then for 1, then for 2

When to pick concatMap

  • When the result order must match the input order.
  • Sequential saga steps, a migration, a command queue.
  • Draft autosave — so an old response can't overwrite newer state.

The cost of the queue

Even if the third task is faster than the first, it has to wait. That's safe for ordering, but slower than mergeMap.

Your task

  1. In pipe, add concatMap(value => timer(value * 20).pipe(map(() => 'Done ' + value))).
  2. Same source 3, 1, 2, but now the order is preserved: Done 3 → Done 1 → Done 2.

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, concatMap, map } = Rx;

const source$ = of(3, 1, 2);

const result$ = source$.pipe(
  concatMap(value => {
    return timer(value * 20).pipe(
      map(() => 'Done ' + value)
    );
  })
);
script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...