Skip to content
jshacks.dev
Async

The RxJS exhaustMap Operator Explained With Examples

Learn how the RxJS exhaustMap operator ignores new values while an inner observable runs, and why it suits submit buttons, logins and refresh actions.

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

exhaustMap is the flattening operator that says no. While one inner observable is running, every new source value is thrown away. Only when the inner observable completes does the operator accept the next value. That sounds like a bug until you picture a submit button: a user who double-clicks "Pay" should create one payment, not two, and not one that is cancelled and restarted. This post explains exhaustMap in RxJS 7 with printed output, shows the dropped values explicitly, compares it with switchMap, concatMap and mergeMap, and covers the situations where silently ignoring input is the wrong choice.

What it does

exhaustMap(project) maps each accepted source value to an inner observable and emits its values. While that inner observable is active, the operator does not call project at all for new source values. It simply discards them. When the inner observable completes, the operator is idle again and the next source value starts a new inner observable.

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

const clicks$ = new Subject();

clicks$
  .pipe(
    exhaustMap((n) => timer(100).pipe(map(() => `finished ${n}`)))
  )
  .subscribe(console.log);

clicks$.next(1);
clicks$.next(2);
clicks$.next(3);

setTimeout(() => clicks$.next(4), 150);
Text
finished 1
finished 4

Clicks 2 and 3 arrived while click 1 was running and vanished. Click 4 arrived at 150 ms, after the first timer completed at 100 ms, so it was accepted and its result printed at about 250 ms.

Proving that the projection is skipped

Because the dropped values never reach project, any work in the projection happens only for accepted values. A log line makes that visible.

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

const source$ = new Subject();

source$
  .pipe(
    exhaustMap((n) => {
      console.log(`project called with ${n}`);
      return of(n).pipe(delay(50));
    })
  )
  .subscribe((n) => console.log(`result ${n}`));

source$.next("a");
source$.next("b");
setTimeout(() => source$.next("c"), 80);
Text
project called with a
result a
project called with c
result c

"b" never called the projection. That matters when the projection has side effects. With concatMap or mergeMap it would have been called, and with exhaustMap it was not.

The submit button

This is the textbook case. A login request takes a moment, the user presses Enter twice, and only one request should leave.

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

const submit$ = new Subject();

function login(credentials) {
  console.log(`POST /login for ${credentials.user}`);
  return of({ ok: true }).pipe(delay(100));
}

submit$
  .pipe(
    exhaustMap((credentials) =>
      login(credentials).pipe(tap(() => console.log("login complete")))
    )
  )
  .subscribe();

submit$.next({ user: "ada" });
submit$.next({ user: "ada" });
submit$.next({ user: "ada" });
Text
POST /login for ada
login complete

One request, one completion. Disabling the button is still good for the user, but it is a UI measure. exhaustMap protects the code path itself, which also covers a double Enter key press, a retried event and a bug that calls the handler twice.

How it differs from switchMap

switchMap also handles overlap, but it favors the newest value and cancels the running work. exhaustMap favors the oldest value and refuses the newcomers.

JavaScript
import { Subject, timer } from "rxjs";
import { exhaustMap, switchMap, map } from "rxjs/operators";

function run(operator, label) {
  const s$ = new Subject();
  s$.pipe(operator((n) => timer(50).pipe(map(() => `${label} ${n}`))))
    .subscribe(console.log);
  s$.next(1);
  s$.next(2);
}

run(switchMap, "switch");
run(exhaustMap, "exhaust");
Text
switch 2
exhaust 1

The difference is which value survives. For a search box, you want the latest query, so switchMap is right. For a one-shot command, you want the first request to finish untouched, so exhaustMap is right.

Refresh actions and polling guards

A "refresh" button that triggers a slow reload is another fit. Clicking it five times while loading should not queue five reloads.

JavaScript
import { interval, of } from "rxjs";
import { delay, exhaustMap, take } from "rxjs/operators";

let calls = 0;

interval(30)
  .pipe(
    take(6),
    exhaustMap(() => {
      calls += 1;
      return of(calls).pipe(delay(100));
    })
  )
  .subscribe((n) => console.log(`reload ${n} finished`));
Text
reload 1 finished
reload 2 finished

The source ticks at 30, 60, 90, 120, 150 and 180 ms. The first tick starts a reload that finishes at 130 ms. Ticks at 60, 90 and 120 ms are dropped. The tick at 150 ms starts the second reload, and the tick at 180 ms is dropped. The exact count depends on timer jitter, but the idea holds: the operator keeps at most one reload in flight. It is also a handy guard for polling that must not overlap when the server is slow.

Errors

An error in the inner observable errors the outer stream, the same as with the other flattening operators. Handle it inside the projection if the stream should survive.

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

const s$ = new Subject();

s$.pipe(
  exhaustMap((n) =>
    (n === 1 ? throwError(() => new Error("failed")) : of(`ok ${n}`)).pipe(
      catchError((e) => of(`handled: ${e.message}`))
    )
  )
).subscribe(console.log);

s$.next(1);
s$.next(2);
Text
handled: failed
ok 2

Because the first inner observable completed after the handled error, the operator was ready for value 2.

When not to use it

When every value matters. If each source value is a different message or edit, dropping any of them loses data. Use concatMap to keep them in order or mergeMap to run them in parallel.

When the user expects the latest input to win. Search, filters and route parameters should use switchMap. With exhaustMap, a user who types a second query while the first is loading would see results for the first one, which looks like the app ignoring them.

When the inner observable never completes. An inner stream such as a websocket or an interval without take keeps the operator busy forever, and every later source value is dropped. Always give the inner observable a completion, using take(1), first() or a source that completes on its own.

When silence is a bad experience. A dropped click gives no feedback. Pair exhaustMap with a visible loading state, so the user sees why nothing else happened.

Choosing between the four

SituationOperator
Latest input should win, old work is disposableswitchMap
Every value must run, in orderconcatMap
Every value must run, in parallelmergeMap
First wins, extra input is noiseexhaustMap

A useful test: ask what should happen if the user acts twice, quickly. If the answer is "the second action replaces the first", it is switchMap. If it is "the second action is ignored", it is exhaustMap.

Pairing it with feedback the user can see

The danger of exhaustMap is not technical, it is human. A person who clicks a second time and sees nothing happen assumes the click was missed and clicks again, or leaves. Because the operator discards input without a sound, the interface has to speak for it. The usual approach is to derive a loading flag from the same stream: set it to true when the projection starts and to false in finalize on the inner observable. The button then shows a spinner and is disabled for exactly as long as the operator is ignoring clicks, and the two states cannot drift apart because they come from the same source.

A second consideration is idempotency on the server. exhaustMap protects one browser tab from sending duplicates. It does nothing for two tabs, a retried request after a network blip, or a mobile client that resumed after being suspended. For anything involving money or inventory, send an idempotency key with the request, so that the server can recognize a repeat and return the first result. The operator removes the common case, and the key covers the rest.

Finally, remember the shape of the guarantee: the first value wins, not the best one. If a user edits a form while a save is running and presses save again, the second values are dropped, and the edits made during the save are not sent. Either lock the form while saving, or switch to concatMap with the latest form state read when the turn comes, so nothing the user typed is lost.

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.