Skip to content
jshacks.dev
Async

The RxJS switchMap Operator Explained With Examples

Learn how the RxJS switchMap operator maps each value to an inner observable and cancels the previous one, and why it fits search boxes and route changes.

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

switchMap answers a specific question: what should happen when a new value arrives while the work started by the previous value is still running? Its answer is to cancel the old work and start the new, so only the latest matters. That behavior is exactly right for search-as-you-type, where a response for "jav" is useless once the user has typed "java", for route parameters where the page should show the latest id and for any request whose result will be replaced. It is also the wrong choice for operations that must finish, such as saving a form, where cancelling is data loss. This post explains switchMap in RxJS 7 with printed output, shows the cancellation happening, covers the autocomplete pattern, compares it with the other three flattening operators, and lists the traps, including the one that bites most often: using it for a write.

What it does

switchMap(project) takes each source value, calls project(value) to get an inner observable and subscribes to it, forwarding its values to the output. When the next source value arrives, switchMap unsubscribes from the current inner observable before subscribing to the new one. The name describes it: it switches to the newest inner observable.

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

const source = of("a", "b").pipe(
  concatMap((value, index) => of(value).pipe(delay(index === 0 ? 0 : 5))),
);

source
  .pipe(
    switchMap((letter) =>
      timer(20).pipe(map(() => `result for ${letter}`)),
    ),
  )
  .subscribe((value) => console.log(value));
Text
result for b

The source emitted a immediately and b five milliseconds later. The inner observable for a, a 20 ms timer, was still pending when b arrived, so switchMap cancelled it, and only the result for b was ever emitted. If a had finished before b arrived, both results would have appeared.

Seeing the cancellation

The inner observable's teardown runs when it is cancelled, which makes the cancellation visible.

JavaScript
import { Observable, timer } from "rxjs";
import { switchMap } from "rxjs/operators";

function request(name) {
  return new Observable((subscriber) => {
    console.log("start", name);
    const id = setTimeout(() => {
      subscriber.next(`response ${name}`);
      subscriber.complete();
    }, 30);

    return () => {
      clearTimeout(id);
      console.log("teardown", name);
    };
  });
}

timer(0, 10)
  .pipe(switchMap((n) => request(`#${n}`)))
  .subscribe();

setTimeout(() => {
  process.exit(0);
}, 25);
Text
start #0
teardown #0
start #1
teardown #1
start #2

Each new timer value cancelled the request before it could answer, and each cancellation ran the teardown, which in real code would abort an HTTP request or close a socket. The program stopped at 25 ms with request #2 still pending. The exact count of lines depends on timer accuracy, and the pattern of start followed by teardown is the point.

The autocomplete pattern

The standard use combines debounceTime, distinctUntilChanged and switchMap.

JavaScript
import { Subject, of } from "rxjs";
import { debounceTime, distinctUntilChanged, switchMap, delay } from "rxjs/operators";

function fakeSearch(query) {
  return of(`results for "${query}"`).pipe(delay(30));
}

const input = new Subject();

input
  .pipe(
    debounceTime(10),
    distinctUntilChanged(),
    switchMap((query) => fakeSearch(query)),
  )
  .subscribe((result) => console.log(result));

input.next("j");
input.next("ja");

setTimeout(() => input.next("jav"), 20);
setTimeout(() => input.next("java"), 35);
Text
results for "java"

The first two keystrokes were merged by debounceTime, so only "ja" started a search. When "jav" arrived, the "ja" search was still in flight and was cancelled, and the same happened to "jav" when "java" arrived. Only the last search completed. Without switchMap, using mergeMap instead, all three responses would have arrived, possibly out of order, and the page could have shown results for an older query. This is the race condition described in the post on race conditions, solved by cancellation.

With HTTP in Angular

In Angular, HttpClient returns cold observables that make a request on subscribe and abort it on unsubscribe, so switchMap cancels the old network request.

TypeScript
this.searchTerm$.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap((term) => this.http.get<Result[]>(`/api/search?q=${term}`)),
).subscribe((results) => (this.results = results));

When a new term arrives, the browser cancels the in-flight request with an abort, and the server may still do the work, since the abort only closes the connection. The benefit is on the client: the stale response never arrives to overwrite the newer one.

Route parameters

Another good fit is reacting to the latest value of something that changes.

TypeScript
this.route.paramMap.pipe(
  map((params) => params.get("id")),
  switchMap((id) => this.service.load(id)),
).subscribe((item) => (this.item = item));

If the user navigates from item 1 to item 2 before item 1 has loaded, the first request is cancelled and the page shows item 2.

Error handling inside

An error from the inner observable ends the whole outer stream, which is usually not what you want in a long-lived pipeline. Catch inside the projection.

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

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

The catchError sits inside the inner pipe, so request 2 failed on its own and the stream carried on with request 3. With catchError after the switchMap, the stream would have ended at the first error.

switchMap versus mergeMap, concatMap and exhaustMap

OperatorNew value arrives while one is runningUse for
switchMapCancels the running one, starts the newSearches, route changes, latest-wins reads
mergeMapStarts the new one, keeps the running oneIndependent parallel work
concatMapQueues the new one until the running one endsOrdered writes, one at a time
exhaustMapIgnores the new valueLogin buttons, anything that must not repeat

Choosing is a matter of asking what the right behavior is for overlapping work. The related posts cover mergeMap, concatMap and exhaustMap.

The trap: writes

Cancelling is a feature for reads and a bug for writes. A switchMap that sends a save request will cancel the previous save when a new value arrives. The request may already have reached the server, so the server may apply it while the client believes it was cancelled, and you can lose track of what was saved.

JavaScript
// risky: a quick second click cancels the first save in flight
saveClicks$.pipe(switchMap((form) => api.save(form))).subscribe();

// safer: ignore clicks while saving
saveClicks$.pipe(exhaustMap((form) => api.save(form))).subscribe();

// or: save every change, in order
changes$.pipe(concatMap((form) => api.save(form))).subscribe();

For anything with side effects, choose exhaustMap or concatMap, and use switchMap only when the cancelled work is harmless to abandon.

Other pitfalls

Forgetting that the result of a cancelled request never arrives. If the UI shows a spinner that stops on response, make sure it also stops when a request is cancelled, with finalize in the inner pipe.

Using it with a source that completes quickly. If the source completes while the last inner observable is running, the output stays alive until that inner finishes, which is correct and sometimes surprising.

Side effects before the switch. A tap before switchMap runs for every source value, including those whose inner work gets cancelled, so counts there will not match results.

Measuring whether cancellation helps

Cancelling a request only helps if something upstream notices. With HttpClient in Angular or fromFetch in RxJS, unsubscribing aborts the browser request, and the network panel shows it as cancelled. With a promise-based source wrapped in from, unsubscribing stops delivery but the request continues, so the saving is only on the client's side, where a stale response no longer lands. Check which of the two you have before explaining the behavior to a teammate, since the difference matters when the server charges for each request or when the work is expensive.

On the server side, a cancelled request is only useful if the server also stops working. Frameworks that expose an abort signal for the incoming request let you pass it down to the database call, so an abandoned query frees its resources. If your backend ignores disconnects, switchMap still gives the user the right result, and it does not reduce the load. Both facts are worth knowing when you decide whether a search endpoint needs a rate limit.

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

Get new posts by email

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

Unsubscribe in one click. No spam, ever.