Sub topic 8
Choosing a Flattening Operator: switchMap, mergeMap, concatMap, exhaustMap
This chapter assumes you know how to use pipe with map and filter, and that you have seen HttpClient return an observable. It covers the case where each value from one stream has to start another async task, such as an HTTP request.
The problem: observables inside observables
If you map each click to an HTTP request, you get an observable that emits observables. Your subscriber receives request objects instead of results, and no request runs, because nothing subscribes to the inner observables.
A flattening operator fixes this. It subscribes to each inner observable for you and passes the inner values on as one flat stream. The four flattening operators differ in one decision: what to do when a new outer value arrives while an earlier inner observable is still running.
| Operator | When a new value arrives during active work | Typical use |
|---|---|---|
| `switchMap` | Cancels the current inner observable and starts the new one | Search-as-you-type, loading data for the selected item |
| `mergeMap` | Runs the new one in parallel with the others | Independent requests where order does not matter |
| `concatMap` | Queues the new one until the current one completes | Ordered writes, sequential uploads |
| `exhaustMap` | Ignores the new value until the current one completes | Login or submit buttons, preventing double-submits |
Seeing the difference
The script below simulates three clicks 300 ms apart. Each click triggers a fake request that takes 1000 ms. Run it with npx tsx flatten.ts or any TypeScript runner that has rxjs installed.
import {
Observable, of, interval, take, map, delay,
switchMap, mergeMap, concatMap, exhaustMap,
} from 'rxjs';
const fakeRequest = (id: number): Observable<string> =>
of(`result ${id}`).pipe(delay(1000));
const clicks$ = interval(300).pipe(take(3), map(i => i + 1));
clicks$.pipe(switchMap(fakeRequest)).subscribe(v => console.log('switchMap ', v));
clicks$.pipe(mergeMap(fakeRequest)).subscribe(v => console.log('mergeMap ', v));
clicks$.pipe(concatMap(fakeRequest)).subscribe(v => console.log('concatMap ', v));
clicks$.pipe(exhaustMap(fakeRequest)).subscribe(v => console.log('exhaustMap', v));The four pipelines behave like this:
switchMaplogs onlyresult 3, because clicks 2 and 3 each cancelled the request in flight.mergeMaplogs results 1, 2, and 3 at about 1.3 s, 1.6 s, and 1.9 s.concatMaplogs results 1, 2, and 3 one second apart, ending at about 3.3 s.exhaustMaplogs onlyresult 1, because clicks 2 and 3 arrived while request 1 was still running.
Deciding which one to use
Common mistakes
- Using
switchMapfor writes. Cancelling an HTTP request unsubscribes on the client, but the server may already have processed the POST. If a save is cancelled this way, you lose the client-side result while the server still applies the change. UseconcatMaporexhaustMapfor mutations. - Unbounded
mergeMap. A fast source can open hundreds of parallel requests. Pass a concurrency limit, for examplemergeMap(fakeRequest, 4). - Putting
catchErroron the outer stream. An error in an inner observable reaches the outer stream and completes it, so later clicks do nothing. PutcatchErrorinside the inner pipe instead, for exampleswitchMap(id => fakeRequest(id).pipe(catchError(() => of('failed')))). - Nested
subscribecalls. Callingsubscribeinside anothersubscribecallback creates inner subscriptions that nothing cancels or tracks. Replace the nesting with a flattening operator.
Exercise
A "Pay now" button sends a POST request. Users sometimes double-click it. Which flattening operator should the click stream use, and why not switchMap?
Show answer
Use exhaustMap. It ignores clicks while the first payment request is in flight, which prevents duplicate submissions. switchMap would cancel the first request on the client, but the server might still charge the card, and a second charge would then follow.
Exercise
A user selects five files, and the files must be uploaded one at a time in the order they were selected. Which operator fits?
Show answer
concatMap. It queues each upload until the previous one completes, so the uploads run sequentially and their results keep their order.