الانتقال إلى المحتوى
FrontendAngular· 7 دقائق للقراءة

switchMap Isn't Always Right: Choosing concatMap, mergeMap or exhaustMap

The four operators differ in one thing: what happens when a new value arrives while a request is still running. For saves, cancelling is usually the wrong answer.

ReadIn

مقال كل يوم يفرق معاك

21 نوفمبر 2026
  • كاتب موثّق
  • Angular 22
محتويات المقال

Support forwards a complaint: a customer was charged twice for one order. The logs show two POST /api/orders requests 300 ms apart, both successful. The checkout component pipes the button's clicks through switchMap, and its author picked it on purpose: "switchMap cancels the duplicate". It did cancel one. The browser aborted the first request when the second click arrived, but the first POST had already reached the server, which created the order anyway. The app showed one confirmation, for the second order.

The common misconception

The belief: switchMap is the safe default for any HTTP call inside an RxJS stream. It cancels whatever is stale, so there are never two requests fighting, and that's as useful for a Save button as it is for a search box.

There are good reasons to believe it. switchMap is the operator in nearly every typeahead example, where it really does fix a : a slow response for "an" can't overwrite the results for "angular". Angular's own HTTP guide points out that combining HttpClient with an operator like switchMap cleans up stale requests, because unsubscribing aborts the request in progress. "Cancels stale work" sounds like a property you'd want everywhere. The catch is the word stale: for a search, the old request is worthless. For a save, the old request is someone's data.

What actually happens

Four operators, one decision

All four are : for each value from the source, they call your function, get an inner Observable (here, an HTTP request) and subscribe to it. As long as each request finishes before the next value arrives, they behave identically. The difference shows only when a value arrives while a request is still in flight:

  • switchMap unsubscribes from the running request and starts the new one. Only the latest result is delivered.
  • concatMap puts the new value in a queue and starts its request when the running one completes. Every request runs, one at a time, in order.
  • mergeMap starts the new request immediately, in parallel. Every request runs, and responses arrive in whatever order the server sends them.
  • exhaustMap ignores the new value. The running request finishes, and only values that arrive after that start a new one.

Cancelling isn't undoing

When switchMap unsubscribes from an HttpClient Observable, the browser aborts the request. That only stops the browser from waiting for an answer. If the request already reached the server, the server may still process it; your app just never learns the result. For a search, that's harmless. For a write, it means a side effect you can't see: a duplicate order, a deleted row that's still in your list, or an autosave of older text that lands after newer text.

So the question for every stream is: if a second value arrives mid-request, what should happen to the first one? For a place-order button, the answer is "nothing new should start", which is exhaustMap.

TypeScript checkout.ts
import { Component, inject } from '@angular/core';import { takeUntilDestroyed } from '@angular/core/rxjs-interop';import { catchError, EMPTY, Subject, switchMap } from 'rxjs';@Component({  selector: 'app-checkout',  template: `<button (click)="placeOrder$.next()">Place order</button>`,})export class Checkout {  private readonly api = inject(OrderApi);  readonly placeOrder$ = new Subject<void>();  constructor() {    this.placeOrder$      .pipe(        // A 2nd click aborts the 1st POST, which may already be saved        switchMap(() =>          this.api.placeOrder().pipe(catchError(() => EMPTY)),        ),        takeUntilDestroyed(),      )      .subscribe((order) => console.log('Created', order.id));  }}

Both versions catch errors inside the inner Observable. An error that reaches the outer stream ends it, with any of the four operators, and the button would silently stop working after the first failed order.

Autosave wants order, not speed

An editor that saves as the user types needs a different answer. Each save matters, and the newest text must be written last. concatMap gives exactly that: it doesn't send the next save until the previous one has completed. The RxJS docs describe it as mergeMap with a concurrency of 1.

TypeScript autosave.ts
import { FormControl } from '@angular/forms';import { concatMap, debounceTime, Observable } from 'rxjs';export function autosave(  text: FormControl<string>,  save: (value: string) => Observable<void>,) {  return text.valueChanges.pipe(    debounceTime(800),    // Each save waits for the previous one to finish    concatMap((value) => save(value)),  );}

The debounceTime() matters here. The RxJS docs warn that if values arrive endlessly and faster than the inner Observables complete, concatMap buffers them without limit. Debouncing keeps the queue short.

Independent writes can run in parallel

Deleting several rows, uploading several files, marking several messages as read: each request stands on its own, and no result should cancel or delay another. That's mergeMap. Its optional concurrent argument, Infinity by default, caps how many requests run at once.

OperatorNew value while a request runsUse it for
switchMapCancels the running requestReads where only the latest matters
concatMapWaits for it to finishWrites that must apply in order
mergeMapRuns alongside itIndependent writes
exhaustMapIs ignoredActions that must not repeat

How to apply it in your project

  1. List every flattening operator that writesSearch for switchMap, mergeMap, concatMap and exhaustMap, and mark each one whose inner call is a POST, PUT, PATCH or DELETE.
  2. Ask the mid-request questionFor each marked stream, decide what a second value should do to the running request: cancel it, wait for it, run alongside it or be ignored. Then pick the operator from the table.
  3. Catch errors insideMove catchError() into the inner Observable, so one failed request reports an error without ending the stream.
  4. Test with a slow networkThrottle the network in DevTools and double-click, type fast and delete rows quickly. Then compare the server's logs with what the UI shows.

Key takeaways

  • The four flattening operators differ only in what happens when a value arrives while a request is still running.
  • switchMap cancels in the browser, not on the server, so it's for reads where only the latest answer matters.
  • Use exhaustMap for actions that must not repeat, concatMap for ordered writes and mergeMap for independent ones.
  • Catch errors inside the inner Observable, whichever operator you choose.

📚 المصادر

  1. switchMap — RxJS
  2. concatMap — RxJS
  3. mergeMap — RxJS
  4. exhaustMap — RxJS
  5. Making HTTP requests — Angular

التعليقات (0)