concatMap vs switchMap in RxJS: cancel or queue?

IntermediateAngular interview questionBy , updated 24 November 2026

Short answer

switchMap and concatMap both map each value to an inner observable, such as an HTTP request, and flatten the results. When a new value arrives while the last inner is still running, switchMap unsubscribes from it and starts the new one, so only the latest result arrives. concatMap waits for the running inner to complete and queues the new value, so every result arrives, in order. Cancel versus queue.

The wider comparison with mergeMap and exhaustMap is in switchMap vs mergeMap vs concatMap vs exhaustMap. This page goes deeper on the two that people mix up most.

The same source through both operators

Take a source that emits a, b and c, and an inner observable that takes 50 ms to emit one result and complete, like a request. In marble notation each character is 10 ms, a letter is a value and | is completion:

source       a-b---c|
request      -----(R|)          (each request: 50 ms, one result)

switchMap    -----------(C|)    only c's result, at 110 ms
concatMap    -----A----B----(C|) all three, in order, at 50, 100 and 150 ms

What happens underneath, event by event:

Time Event switchMap concatMap
0 ms a arrives Starts request a Starts request a
20 ms b arrives Unsubscribes from a, starts b Puts b in its buffer
50 ms Request a would finish Nothing: a was cancelled Emits A, starts b
60 ms c arrives Unsubscribes from b, starts c Puts c in its buffer
100 ms Request b would finish Nothing: b was cancelled Emits B, starts c
110 ms Request c finishes Emits C, completes
150 ms Request c finishes Emits C, completes

Both complete only when the source has completed and nothing is left running. For concatMap that also means an empty buffer, which is why its completion comes 40 ms later.

You can check this yourself with RxJS's TestScheduler, which runs marble diagrams on virtual time:

import { concatMap, switchMap } from "rxjs";
import { TestScheduler, type RunHelpers } from "rxjs/testing";

const test = () => new TestScheduler((actual, expected) => expect(actual).toEqual(expected));
const request = (cold: RunHelpers["cold"]) => (v: string) =>
  cold("-----(r|)", { r: v.toUpperCase() });

test().run(({ cold, expectObservable }) => {
  expectObservable(cold("a-b---c|").pipe(switchMap(request(cold)))).toBe("-----------(r|)", { r: "C" });
});

test().run(({ cold, expectObservable }) => {
  expectObservable(cold("a-b---c|").pipe(concatMap(request(cold)))).toBe("-----A----B----(C|)");
});

Cancellation versus queueing

switchMap keeps at most one inner subscription. On every new value it calls unsubscribe() on the current inner before subscribing to the next. The old inner's later values are never delivered, and its teardown runs straight away.

concatMap is mergeMap with a concurrency of 1, and the RxJS 7 docs say so directly. It keeps one active inner and an array of waiting values. When the active inner completes, it takes the next value from the array, calls your project function with it and subscribes. Two details follow from that:

  • The project function for a queued value runs when its turn comes, not when the value arrives. A request is only built then, but it is built from the value captured at arrival time, not the latest state.
  • An inner that never completes, such as interval() or a websocket stream, blocks the queue for ever. concatMap only moves on when the inner completes.

What happens to in-flight HTTP requests

Angular's HttpClient returns cold observables, and the Angular docs state that unsubscribing aborts the request in progress. So switchMap over HttpClient cancels at the network level: in DevTools the old request shows as cancelled, and with the withFetch() backend it is aborted through an AbortController.

// Each new route id aborts the request for the previous one
product = toSignal(
  this.route.paramMap.pipe(
    map((params) => params.get("id")!),
    switchMap((id) => this.http.get<Product>(`/api/products/${id}`)),
  ),
);

Cancellation happens only on the client. If the server already received the request, it may still process it. And if your inner observable wraps a promise, for example from(fetch(url)), unsubscribing ignores the result but does not abort anything. For a real abort, create the observable with a teardown that calls controller.abort(), or use fromFetch from rxjs/fetch.

concatMap never cancels. Every request is sent and its response is delivered, one after another.

When switchMap is wrong: saves lose writes

Using switchMap for writes is the classic bug:

// Wrong: a quick second edit aborts the first save
this.form.valueChanges.pipe(
  debounceTime(500),
  switchMap((value) => this.api.patch(value)),
).subscribe();

Three things can go wrong:

  • If each request carries only the changed fields, an aborted request means those fields never reach the server. The write is lost.
  • If the server did receive the aborted request, it may still commit it, and because it is still being processed it can finish after the newer one and overwrite it with older data.
  • The client never sees the aborted request's response or error, so it cannot show "Saved" or retry.

Use concatMap for writes that must all happen in order, or exhaustMap when extra triggers should be dropped, such as a double click on Pay.

When concatMap is wrong: typeahead builds a backlog

// Wrong: every query waits for all the earlier ones
this.query.valueChanges.pipe(
  debounceTime(300),
  concatMap((q) => this.api.search(q)),
).subscribe((results) => this.results.set(results));

If the user pauses longer than the debounce but shorter than the server takes to answer, requests queue up. The list shows the results for the first query, then the second, and only later the one the user wants, each replacing the last. Typing faster than the server answers makes the queue grow, so the lag grows too. Nothing is wrong with the data, but the UI keeps showing answers to questions the user has stopped asking. Search is a "latest wins" read, so use switchMap.

Memory and backpressure in concatMap

RxJS has no backpressure: an operator cannot ask its source to slow down. concatMap therefore buffers every value that arrives while an inner is running, and the buffer has no limit. The RxJS 7 docs warn that if values arrive endlessly and faster than inners can complete, memory grows without bound.

For a save queue that is usually harmless, because a human types slower than a server answers. It becomes a problem with fast sources: mousemove, a websocket feed, scroll, or a server that has slowed down. Ways to keep the buffer small:

  • Thin the source first. debounceTime, auditTime or throttleTime before concatMap cap how fast values can join the queue.
  • Coalesce. For autosave, only the newest pending value matters. RxJS has no built-in "queue, but keep only the latest" operator, so autosave code usually keeps one save in flight and one latest value waiting. That is exactly what an autosave hook that never loses edits asks you to build.
  • Watch the inner. A slow or hanging inner stalls everything behind it. Add timeout() inside the inner so one stuck request cannot block the queue.

Errors and unsubscribing

An error from any inner errors the whole result for both operators. With concatMap that also throws away everything still in the buffer, so one failed save discards the saves queued behind it. Put catchError inside the project function so a failure ends only that inner.

Unsubscribing from the result, for example through takeUntilDestroyed() when a component is destroyed, aborts the running request and drops the buffer. If queued saves must survive navigation, run the queue in a service that outlives the component, or flush it before leaving.

Side by side

switchMap concatMap
New value while busy Unsubscribes from the current inner, starts the new one Buffers the value until the current inner completes
Inners running at once At most one Exactly one, others waiting
Results delivered Only the latest inner's Every inner's, in source order
In-flight HttpClient request Aborted on the client Always runs to the end
Memory Constant Buffer grows if values arrive faster than inners finish
Inner that never completes Replaced by the next value Blocks the queue
Latency for the latest value Starts at once Waits for everything queued before it
Good for Search, route params, filters, any "latest wins" read Ordered writes, autosave, sequential steps
Wrong for Saves, payments, anything every request must finish Typeahead and other reads where old answers are useless

Follow-up questions interviewers ask

Is concatMap the same as mergeMap with concurrency 1?

Yes. RxJS 7 implements concatMap(project) as mergeMap(project, 1). Raising the number gives a bounded parallel queue, which suits uploads.

Does switchMap guarantee the server never processes the old request?

No. It aborts on the client. A request the server already received may still run to completion, which is why switchMap belongs on reads.

Why can't concatMap work with an inner that never completes?

It starts the next inner only after the current one completes. Add take(1), first() or takeUntil() to the inner, or use switchMap if the latest stream should replace the old one.

How do you implement switchMap without RxJS?

Keep a request id or an AbortController per request and abort the previous one when a new value arrives. Search-as-you-type with debounce and AbortController is that exercise, and Observables vs promises in Angular explains why promises need the extra work.

Which would you use for a "load more" button?

Usually exhaustMap, so extra clicks during a load are ignored. concatMap would load one page per click, in order, which is acceptable if every click should load a page. switchMap would cancel a half-loaded page, which is rarely what anyone wants. The full four-way comparison is in the wider operator guide.

Practise it in code

Interviewers rarely stop at the definition. These questions open in an editor with tests.

  1. Implement RxJS switchMap, mergeMap, concatMap and exhaustMap with correct completion and teardownHard55 min
  2. Implement switchMap, concatMap and exhaustMap for async request streamsHard55 min
  3. Build an autosave hook that debounces, coalesces and never loses editsMedium45 min
  4. Build search-as-you-type with debounce and AbortControllerMedium35 minFree
  5. Build a typeahead/autocomplete with caching and keyboard supportMedium45 minFree