Skip to content
jshacks.dev
Async

The RxJS concatMap Operator Explained With Examples

Learn how the RxJS concatMap operator runs inner observables one at a time in order, where it fits in real code and what its queue does under load.

7 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the JavaScript, RabbitMQ, Node.js and Redis logos.

concatMap is the flattening operator for work that must happen in order. For every value from the source it creates an inner observable, but it subscribes to only one inner observable at a time. Values that arrive while one is running wait in an internal queue, and each starts only after the previous one completes. That makes it the stream version of awaiting inside a for loop. It is the safe default for writes, such as saving edits or sending messages in sequence, and it has one failure mode you should know before shipping it: the queue is unbounded. This post explains concatMap in RxJS 7 with printed output, shows how it differs from mergeMap, switchMap and exhaustMap, and covers the mistakes that matter in practice.

What it does

concatMap(project) calls project with each source value and the index, expects an observable (or promise, array or iterable) back, and emits everything that inner source emits. The difference from mergeMap is the subscription rule: it waits for the active inner source to complete before subscribing to the next one.

JavaScript
import { of, timer } from "rxjs";
import { concatMap, map } from "rxjs/operators";

of("a", "b", "c")
  .pipe(
    concatMap((letter) =>
      timer(100).pipe(map(() => letter.toUpperCase()))
    )
  )
  .subscribe((value) => console.log(value));
Text
A
B
C

All three source values arrive at once, but the inner timers run back to back, so the output appears at roughly 100, 200 and 300 ms. With mergeMap the three timers would run together and the output would appear at about 100 ms.

Order is guaranteed, and so is a wait

The guarantee is the point. Results come out in the same order as the source values, regardless of how long each inner observable takes. Here the first inner source is the slowest.

JavaScript
import { of, timer } from "rxjs";
import { concatMap, map } from "rxjs/operators";

const delays = { first: 300, second: 100, third: 200 };

of("first", "second", "third")
  .pipe(
    concatMap((name) =>
      timer(delays[name]).pipe(map(() => `${name} done`))
    )
  )
  .subscribe(console.log);
Text
first done
second done
third done

With mergeMap the same code prints second done, third done, first done, because each result is emitted when its timer fires. With concatMap, second could be ready at 100 ms and still waits until first completes at 300 ms. The total time is the sum of the delays, 600 ms, not the longest one. If you do not need the order, you are paying for it.

The queue behind it

Internally concatMap is mergeMap with concurrent set to 1. Source values that arrive while an inner source is active are buffered in memory. You can watch the buffering with a source that emits faster than the inner work finishes.

JavaScript
import { interval, timer } from "rxjs";
import { concatMap, map, take, tap } from "rxjs/operators";

interval(50)
  .pipe(
    take(4),
    tap((n) => console.log(`source ${n}`)),
    concatMap((n) =>
      timer(120).pipe(map(() => `handled ${n}`))
    )
  )
  .subscribe(console.log);
Text
source 0
source 1
source 2
source 3
handled 0
handled 1
handled 2
handled 3

The source finished emitting at about 150 ms, while the first result only arrived at about 170 ms. By then values 1, 2 and 3 were already waiting. Handled results then appear every 120 ms. Exact timing varies by machine, but the order of the lines does not. For a bounded source this is fine. For an endless one, such as mouse moves or websocket messages, a slow inner operation makes the queue grow without limit, and nothing in the operator warns you.

A real use: saving in sequence

The classic fit is a form that autosaves. Each change produces a save request, the server must apply them in order, and a later save must not overtake an earlier one.

JavaScript
import { Subject, of } from "rxjs";
import { concatMap, delay } from "rxjs/operators";

const changes$ = new Subject();

function save(value) {
  return of(`saved ${value}`).pipe(delay(50));
}

changes$.pipe(concatMap((value) => save(value))).subscribe(console.log);

changes$.next("draft 1");
changes$.next("draft 2");
changes$.next("draft 3");
Text
saved draft 1
saved draft 2
saved draft 3

If you used switchMap here, saves 1 and 2 would be cancelled and only the third would complete, which is acceptable only if the server treats every save as a full replacement and the cancelled requests did not already change anything. If you used mergeMap, the three requests would race, and the server could end up with draft 2 as the final state. concatMap is the version that is correct without having to reason about either problem.

Errors stop the whole stream

An error in any inner observable errors the output and discards the queue. One failed save would silently drop everything waiting behind it.

JavaScript
import { of, throwError } from "rxjs";
import { concatMap, catchError } from "rxjs/operators";

of(1, 2, 3)
  .pipe(
    concatMap((n) =>
      n === 2 ? throwError(() => new Error("bad 2")) : of(n)
    )
  )
  .subscribe({
    next: (n) => console.log("value", n),
    error: (e) => console.log("error", e.message),
    complete: () => console.log("complete"),
  });
Text
value 1
error bad 2

Value 3 never ran. The fix is to handle the error inside the projection, so the outer stream keeps going.

JavaScript
import { of, throwError } from "rxjs";
import { concatMap, catchError } from "rxjs/operators";

of(1, 2, 3)
  .pipe(
    concatMap((n) =>
      (n === 2 ? throwError(() => new Error("bad 2")) : of(n)).pipe(
        catchError((e) => of(`failed: ${e.message}`))
      )
    )
  )
  .subscribe(console.log);
Text
1
failed: bad 2
3

Each item now reports its own failure, and the queue continues. Decide per use case whether a failed item should be skipped, retried or should stop the line, and write that decision into the inner catchError instead of leaving it to chance.

Choosing between the four flattening operators

OperatorNew value while one runsOrder of outputTypical use
concatMapqueuedsame as sourceordered writes
mergeMapruns in parallelby completion timeindependent lookups
switchMapcancels the old onelatest onlysearch, navigation
exhaustMapignoredfirst one winssubmit buttons

A rule that works well: if losing a value would be a bug, use concatMap or mergeMap. If stale values are the bug, use switchMap. If extra values are the bug, use exhaustMap.

Common mistakes

Using it on an infinite fast source without a limit. If events arrive faster than the work finishes, memory grows. Put throttleTime, auditTime or bufferTime in front, or choose exhaustMap when dropping is acceptable.

Expecting it to start the next item immediately on emission. The next inner observable starts on completion. An inner observable that never completes, such as an interval without take, blocks the queue forever, and every later value waits behind it.

Returning a hot observable from the projection. concatMap subscribes late to inner sources that it has queued. If the inner source is hot, values emitted before the subscription are lost. Wrap work in defer or return cold observables.

Forgetting that the order is of subscription, not of creation. A project function that starts a promise runs immediately for every queued item, because the promise begins as soon as it is created. Use defer(() => fetch(...)) so the request starts only when the queue reaches it.

JavaScript
import { of, defer } from "rxjs";
import { concatMap } from "rxjs/operators";

const log = [];

of(1, 2)
  .pipe(
    concatMap((n) =>
      defer(() => {
        log.push(`start ${n}`);
        return Promise.resolve(n);
      })
    )
  )
  .subscribe((n) => log.push(`got ${n}`))
  .add(() => {});

setTimeout(() => console.log(log.join(", ")), 0);
Text
start 1, got 1, start 2, got 2

The second request began only after the first one had been delivered, which is what the queue is for. Without defer the promise for item 2 would have started at the same moment as item 1.

Deciding whether the order is worth its price

Ordering is the reason to reach for concatMap, and ordering has a cost that is easy to forget until a dashboard shows it. Work that could have overlapped now waits its turn, so the slowest item in front of the queue delays everything behind it. A single request that hangs for thirty seconds holds up every save that follows, and the user sees "saving" for as long as the queue is long. Two measures keep that under control. First, put a timeout on the inner observable, so a stuck item fails and moves on instead of blocking. Second, decide what a failed item means for the items behind it, because in a queue of edits to the same document, applying edit 3 after edit 2 failed may be worse than stopping.

A good habit is to ask what the server does if the requests arrive in the wrong order. If the answer is "nothing bad", you may not need concatMap at all, and mergeMap with a concurrency cap will finish sooner. If the answer is "the document ends up wrong", the queue is doing real work and its latency is the price of correctness.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

6 min read
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka, Redis and RabbitMQ logos.
Node.js

The Node.js Event Loop Phases Explained

Learn the six phases of the Node.js event loop, where timers, I/O, setImmediate, process.nextTick and promises run, and why their order sometimes surprises you.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.