Skip to content
jshacks.dev
Async

The RxJS mergeMap Operator Explained With Examples

Learn how the RxJS mergeMap operator runs inner observables in parallel, how its concurrent limit works and when its unordered results cause problems.

6 min read
Summarize in AI
Flat illustration of a heartbeat line above application health tiles, with the Prometheus and Redis logos.

mergeMap is the flattening operator that does the most work at once. For every value from the source it starts an inner observable, and it keeps all of them running, merging whatever they emit into one output stream. Nothing is cancelled, nothing is queued and nothing is ignored. That makes it the direct counterpart of Promise.all for streams, and it is the right choice for independent work, such as fetching details for each id in a list or handling each incoming message separately. It also carries two risks that the other flattening operators avoid: results come out in the order the inner observables finish and not the order they started, and an unbounded number of them can run at the same time. This post explains mergeMap in RxJS 7 with printed output, shows the interleaving, introduces the concurrent argument that limits parallelism, compares it with switchMap, concatMap and exhaustMap and lists the mistakes that matter. It was formerly known as flatMap, which still exists as an alias.

What it does

mergeMap(project) calls project(value) for each source value, subscribes to the returned inner observable, promise or iterable straight away and forwards each inner value to the output. The output completes when the source and all the inner observables have completed.

JavaScript
import { of } from "rxjs";
import { mergeMap } from "rxjs/operators";

of(1, 2, 3)
  .pipe(mergeMap((n) => of(n * 10, n * 10 + 1)))
  .subscribe((value) => console.log(value));
Text
10
11
20
21
30
31

Each source value produced two values, and mergeMap merged them. Because every inner observable here completes synchronously, the output follows the input order. That changes as soon as the inner observables take time.

Interleaving

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

of(
  { id: "a", delay: 30 },
  { id: "b", delay: 10 },
  { id: "c", delay: 20 },
)
  .pipe(
    mergeMap(({ id, delay }) => timer(delay).pipe(map(() => `finished ${id}`))),
  )
  .subscribe((value) => console.log(value));
Text
finished b
finished c
finished a

The three timers started together, and results arrived in the order they finished: b, then c, then a. The order of the source was lost. If you need results in source order, use concatMap, or collect with forkJoin and sort afterwards. If you need to know which source value a result belongs to, return an object that carries the identifier, as the finished string does here.

Parallel requests for a list of ids

The most common use is turning a list of ids into a stream of responses.

JavaScript
import { from, of } from "rxjs";
import { mergeMap, delay, toArray } from "rxjs/operators";

function fetchUser(id) {
  return of({ id, name: `user ${id}` }).pipe(delay(10));
}

from([1, 2, 3, 4])
  .pipe(
    mergeMap((id) => fetchUser(id)),
    toArray(),
  )
  .subscribe((users) => console.log(users.map((u) => u.id).sort()));
Text
[ 1, 2, 3, 4 ]

All four requests start immediately, and toArray collects the results when the stream completes. The sort in the log makes the output deterministic, since completion order is not guaranteed. For a list that fits comfortably in memory and a server that can take all the requests at once, this is both simple and fast.

Limiting concurrency

The second numeric argument, concurrent, caps how many inner observables run at once. Extra source values wait in a buffer until a slot frees up.

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

let running = 0;
let peak = 0;

from([1, 2, 3, 4, 5, 6])
  .pipe(
    mergeMap(
      (n) => {
        running += 1;
        peak = Math.max(peak, running);

        return timer(10).pipe(
          map(() => {
            running -= 1;
            return n;
          }),
        );
      },
      2,
    ),
  )
  .subscribe({ complete: () => console.log("peak concurrent:", peak) });
Text
peak concurrent: 2

Six units of work ran two at a time. This is the answer to the limit that [Promise.all lacks](/library/promise-all-run-parallel-fail-fast), and it is why mergeMap(fn, 5) is the standard way to call an API for every item in a long list without opening hundreds of connections. mergeMap(fn, 1) behaves exactly like concatMap.

Pick the limit from what the receiver can handle. Browsers allow around six simultaneous connections per host over HTTP/1.1, a database pool has a fixed size and an API may rate limit. Starting with a small number such as four or five and raising it while measuring is safer than starting unbounded.

Handling many incoming messages

Another natural use is a source of events that each trigger independent asynchronous work.

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

const messages = new Subject();

messages
  .pipe(mergeMap((message) => of(`handled ${message}`).pipe(delay(message === "slow" ? 30 : 5))))
  .subscribe((result) => console.log(result));

messages.next("slow");
messages.next("fast");
Text
handled fast
handled slow

A slow message did not hold up the fast one behind it. For a server that handles independent requests, that is the property you want, and it is why mergeMap is the default choice when order and cancellation do not matter.

Errors

As with switchMap, an error in an inner observable ends the whole output. Catch inside the projection to isolate failures.

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

from([1, 2, 3])
  .pipe(
    mergeMap((n) =>
      (n === 2 ? throwError(() => new Error("boom")) : of(`ok ${n}`)).pipe(
        catchError((error) => of(`failed ${n}: ${error.message}`)),
      ),
    ),
  )
  .subscribe((value) => console.log(value));
Text
ok 1
failed 2: boom
ok 3

Without the inner catchError, the error would terminate the output and cancel the other running inner observables.

Using promises

The projection may return a promise, an array or any iterable, and mergeMap accepts them as inner sources.

JavaScript
import { of } from "rxjs";
import { mergeMap } from "rxjs/operators";

of(1, 2, 3)
  .pipe(mergeMap(async (n) => n * 2))
  .subscribe((value) => console.log(value));
Text
2
4
6

An async function returns a promise, so each source value starts a promise and mergeMap emits the settled value. The promises start eagerly and cannot be cancelled, so unsubscribing stops delivery but not the work.

Choosing among the four

OperatorOverlap policy
mergeMapRun all at once, up to the concurrent limit; output in completion order
concatMapOne at a time, in source order
switchMapCancel the running one when a new value arrives
exhaustMapIgnore new values while one is running

If the order of results matters, prefer concatMap. If only the latest matters, use switchMap. If a repeat must be blocked, use exhaustMap. Use mergeMap when the pieces are independent and speed matters more than order.

Common mistakes

Unbounded fan-out. A source of ten thousand values with plain mergeMap starts ten thousand inner subscriptions. Pass a concurrent limit.

Assuming order. Results arrive in completion order. Tag them or use concatMap if order is required.

Using it for writes that conflict. Two saves to the same record running in parallel can finish in either order, leaving the older data last. Use concatMap for ordered writes to one resource.

Forgetting to complete the source. The output completes only when the source and every inner observable complete. A long-lived source keeps it open, which is expected and sometimes mistaken for a hang.

When parallel is the wrong default

It is tempting to treat parallel as faster and therefore better, and mergeMap makes that the path of least resistance. The better question is what the receiver can absorb. A hundred parallel requests to one service may be slower overall than ten at a time, because the service queues them, and may trigger rate limiting or failures that cost more time through retries. A good default for calls to a shared dependency is a concurrency of four to eight, and a measurement before raising it.

Parallel work also changes failure behavior. With many inner observables running, one failing request can cancel the rest if the error is not caught inside, and a result that arrives late can overwrite a newer one. Tag results with identifiers, order them explicitly when order matters and think about what the system should do when only some of the requests succeed. Those decisions belong in the design, not in a surprise discovered under load.

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.