
switchMap Isn't Always Right: Choosing concatMap, mergeMap or exhaustMap
- كاتب موثّق
- Angular 22
محتويات المقال
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
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.
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
switchMapunsubscribes from the running request and starts the new one. Only the latest result is delivered.concatMapputs the new value in a queue and starts its request when the running one completes. Every request runs, one at a time, in order.mergeMapstarts the new request immediately, in parallel. Every request runs, and responses arrive in whatever order the server sends them.exhaustMapignores the new value. The running request finishes, and only values that arrive after that start a new one.
Cancelling isn't undoing
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.
exhaustMap.
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)); }}import { Component, inject } from '@angular/core';import { takeUntilDestroyed } from '@angular/core/rxjs-interop';import { catchError, EMPTY, exhaustMap, Subject } 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( // Clicks while an order is pending are ignored exhaustMap(() => this.api.placeOrder().pipe(catchError(() => EMPTY)), ), takeUntilDestroyed(), ) .subscribe((order) => console.log('Created', order.id)); }}Autosave wants order, not speed
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.
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)), );}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
mergeMap. Its optional concurrent argument, Infinity by default, caps how many requests run at once.
switchMap | ||
concatMap | ||
mergeMap | ||
exhaustMap |
How to apply it in your project
List every flattening operator that writes Search for switchMap,mergeMap,concatMapandexhaustMap, and mark each one whose inner call is aPOST,PUT,PATCHorDELETE.Ask the mid-request question For 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. Catch errors inside Move catchError()into the inner Observable, so one failed request reports an error without ending the stream.Test with a slow network Throttle 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. switchMapcancels in the browser, not on the server, so it's for reads where only the latest answer matters.Use exhaustMapfor actions that must not repeat,concatMapfor ordered writes andmergeMapfor independent ones.Catch errors inside the inner Observable, whichever operator you choose.
التعليقات (0)