Sub topic 8
Choosing a Flattening Operator: switchMap, mergeMap, concatMap, exhaustMap
This chapter assumes you know how pipe and basic operators such as map work, how HttpClient returns observables, and how catchError recovers from errors. It also uses takeUntilDestroyed, which an earlier chapter covered.
Many real tasks involve dependent async work. A user action happens, and each action starts a request. The action is one stream and each request is another. Flattening operators connect the two. Choosing the wrong one gives you race conditions, duplicate submissions, or requests that never stop.
The Problem: Observables Inside Observables
Suppose each click should trigger an HTTP call. With map alone, you get this:
import { Observable, map, of, timer } from 'rxjs';
const clicks$ = timer(0, 100);
const request = (id: number): Observable<string> => of(`result ${id}`);
const nested$: Observable<Observable<string>> = clicks$.pipe(
map(id => request(id))
);The type Observable<Observable<string>> is a higher-order observable. That means the outer stream emits other observables. Nobody subscribes to the inner ones, so no request ever runs.
Some people fix this with a subscribe inside a subscribe. That approach breaks cancellation and error handling, and it leaks subscriptions. A flattening operator is the correct fix. It subscribes to each inner observable for you and merges the inner values into one output stream.
All four operators have the same shape: xMap(value => innerObservable$). They differ in one thing: what happens when a new outer value arrives while an earlier inner observable is still running.
The Four Strategies
| Operator | When a new outer value arrives while an inner one is active | Typical use |
|---|---|---|
| `switchMap` | Unsubscribes from the current inner and switches to the new one | Search, route params, "latest value wins" reads |
| `mergeMap` | Runs the new inner alongside the others | Independent parallel work, such as deleting many items |
| `concatMap` | Queues the new inner until the current one completes | Ordered writes, such as autosave |
| `exhaustMap` | Ignores the new outer value | Login and submit buttons, refresh triggers |
Seeing the Difference Run
The script below simulates three clicks 100 ms apart. Each click starts a fake request that takes 250 ms. It runs all four strategies on the same input.
import {
Observable,
OperatorFunction,
concatMap,
exhaustMap,
map,
mergeMap,
switchMap,
take,
timer,
} from 'rxjs';
const start = Date.now();
const elapsed = () => `${Math.round((Date.now() - start) / 50) * 50}ms`;
function fakeRequest(id: number): Observable<string> {
return timer(250).pipe(map(() => `result ${id}`));
}
// Emits 0, 1, 2 at roughly 0 ms, 100 ms, and 200 ms, then completes.
const clicks$ = timer(0, 100).pipe(take(3));
const runs: [string, OperatorFunction<number, string>][] = [
['switchMap', switchMap(fakeRequest)],
['mergeMap', mergeMap(fakeRequest)],
['concatMap', concatMap(fakeRequest)],
['exhaustMap', exhaustMap(fakeRequest)],
];
for (const [name, operator] of runs) {
clicks$.pipe(operator).subscribe({
next: value => console.log(`${elapsed()} ${name}: ${value}`),
complete: () => console.log(`${elapsed()} ${name}: complete`),
});
}Grouped by operator, the output looks like this (timings are approximate):
| Operator | Emissions |
|---|---|
| `switchMap` | `result 2` at about 450 ms |
| `mergeMap` | `result 0` at 250, `result 1` at 350, `result 2` at 450 |
| `concatMap` | `result 0` at 250, `result 1` at 500, `result 2` at 750 |
| `exhaustMap` | `result 0` at 250 only |
With switchMap, requests 0 and 1 were cancelled before they finished. With exhaustMap, clicks 1 and 2 arrived while request 0 was still busy, so they were dropped. The concatMap run takes the longest because it runs one request at a time.
switchMap: Latest Value Wins
Use switchMap for reads where an older answer is useless once a newer request exists. Route parameters are a good example. Searches are another, and the next chapter builds a full one. When switchMap unsubscribes from an HttpClient observable, Angular aborts the underlying XHR or fetch request.
concatMap: Ordered Writes
Autosave is the textbook concatMap case. Every edit must reach the server, and they must arrive in order. If they ran in parallel, an older save could finish last and overwrite a newer one.
import { Component, inject } from '@angular/core';
import { FormControl, ReactiveFormsModule } from '@angular/forms';
import { HttpClient } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { catchError, concatMap, of } from 'rxjs';
@Component({
selector: 'app-note-editor',
standalone: true,
imports: [ReactiveFormsModule],
template: `<textarea [formControl]="note"></textarea>`,
})
export class NoteEditorComponent {
private http = inject(HttpClient);
note = new FormControl('', { nonNullable: true });
constructor() {
this.note.valueChanges
.pipe(
concatMap(text =>
this.http.put('/api/note', { text }).pipe(catchError(() => of(null)))
),
takeUntilDestroyed()
)
.subscribe();
}
}The gotcha is unbounded queueing. If edits arrive faster than saves finish, the queue grows without limit. In production you would usually add debounceTime before concatMap.
exhaustMap: Ignore While Busy
exhaustMap prevents double submission. While a login request is running, extra clicks do nothing. The example uses a Subject so the click handler can push values into a stream. A later chapter covers subjects in detail.
import { Component, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { takeUntilDestroyed } from '@angular/core/rxjs-interop';
import { Subject, catchError, exhaustMap, of } from 'rxjs';
@Component({
selector: 'app-login',
standalone: true,
template: `
<button (click)="submit()">Sign in</button>
<p>{{ status }}</p>
`,
})
export class LoginComponent {
private http = inject(HttpClient);
private submit$ = new Subject<void>();
status = '';
constructor() {
this.submit$
.pipe(
exhaustMap(() =>
this.http
.post<{ token: string }>('/api/login', { user: 'demo' })
.pipe(catchError(() => of(null)))
),
takeUntilDestroyed()
)
.subscribe(result => (this.status = result ? 'Signed in' : 'Login failed'));
}
submit(): void {
this.submit$.next();
}
}The dropped clicks leave no trace. If users need feedback, disable the button while the request runs, as well as using exhaustMap.
mergeMap: Parallel and Independent
Use mergeMap when each inner task stands alone and order doesn't matter. Its optional second argument limits how many inner subscriptions run at the same time.
import { Injectable, inject } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, from, mergeMap, toArray } from 'rxjs';
@Injectable({ providedIn: 'root' })
export class BulkDeleteService {
private http = inject(HttpClient);
deleteAll(ids: number[]): Observable<number[]> {
return from(ids).pipe(
mergeMap(id => this.http.delete<number>(`/api/items/${id}`), 3),
toArray()
);
}
}Without the limit of 3, a list of 500 IDs would fire 500 requests at once. Results also come back in completion order, not input order. mergeMap(fn, 1) behaves exactly like concatMap(fn).
Failure Modes That Apply to All Four
An inner error kills the outer stream
If an inner observable errors, the error passes through the flattening operator. The outer subscription then ends, and later clicks or keystrokes do nothing. Put catchError inside the inner pipe, as the examples above do, so that only the failed request is replaced.
Inner observables that never complete
concatMap and exhaustMap wait for the current inner observable to complete. If the inner is interval or a valueChanges stream, it never completes. concatMap then queues forever and exhaustMap ignores everything after the first value. HTTP observables complete after one response, so they are safe.
Outer completion
The output completes only when the outer stream and every active inner stream have completed. A stream such as valueChanges never completes, so you still need takeUntilDestroyed or the async pipe.
Exercise
A "Refresh" button reloads a dashboard with a GET request that takes about 2 seconds. Users often click it several times quickly. Which flattening operator fits best, and why might switchMap be a reasonable second choice?
Show answer
exhaustMap fits best: the first click starts the request and later clicks are ignored until it completes, so the server gets one request per burst. switchMap also works because the request is a read with no side effects, but each click cancels and restarts the request, so the data arrives later and more load reaches the server.
Exercise
This code stops responding after the first failed request: clicks$.pipe(switchMap(() => http.get('/api/data')), catchError(() => of(null))). Explain why and fix it.
Show answer
The inner error passes through switchMap to the outer stream. catchError replaces it with of(null), which emits once and completes, so the whole subscription ends. Move catchError into the inner pipe: clicks$.pipe(switchMap(() => http.get('/api/data').pipe(catchError(() => of(null))))).
Exercise
You upload 40 files with mergeMap and no concurrency argument, and the browser stalls. What change keeps uploads parallel but bounded, and what happens to the order of results?
Show answer
Pass a concurrency limit, for example mergeMap(file => upload(file), 4), so at most four uploads run at once. Results still come back in completion order, not input order. If order matters, sort the results afterward or use concatMap and accept the slower sequential uploads.