| | |

RxJS 07 ๐ŸŸฃ Higher-Order Mapping (Flattening) โ€” Preventing race conditions with switchMap, mergeMap, concatMap, and exhaustMap

โฑ๏ธ Estimated read: 25 min | |

A higher-order observable is an observable whose values are themselves observables. It appears the moment an operator maps each outer value into an asynchronous stream โ€” a switchMap((id) => http.get(\/users/${id}`))returnsObservable, but the operator's input is Observableand its intermediate result isObservable<Observable>`. Flattening means subscribing to those inner observables and delivering their values as one flat sequence. The four operators in this chapter are all flatteners; they differ by one and only one rule โ€” what happens to an inner subscription when a new outer value arrives.

That single rule determines everything else: whether results arrive out of order, whether the network is flooded, whether a form can double-submit, whether a route change can leak a stale response. switchMap cancels the previous inner. mergeMap keeps them all running in parallel. concatMap queues them behind each other. exhaustMap ignores new outer values while an inner is still active. Choosing wrong is not a style issue โ€” it is the difference between one POST and two, between sixty requests and six, between showing user 2’s data after user 3 clicked.

This chapter starts with why higher-order observables need flattening at all, then walks through each of the four operators and the exact rule it applies, then shows a side-by-side session where the same outer stream is routed through all four so the difference becomes visible on real output.

Key point: all four operators flatten outer values into inner observables; they are distinguished entirely by their inner-subscription policy โ€” cancel (switchMap), keep all parallel (mergeMap), queue and serialise (concatMap), or ignore new until idle (exhaustMap). Pick the operator by asking what should happen to the previous inner when a new outer value arrives.


Why higher-order mapping exists

The nested-subscribe problem. Before flattening operators, the only way to chain an async call off another was to subscribe inside a subscribe. That idiom leaks: the inner subscription is never stored, so it cannot be cancelled, and if the outer emits again the old inner keeps delivering values into a callback that has already been overwritten. The bug is subtle because it only shows up under racing events, and the fix in every case is the same โ€” move the inner subscription inside the flattening operator so its lifecycle is managed for you.

The subscription leak. Any intro-observable from HttpClient, fromEvent, or interval opens a real resource: a network connection, an event listener, a timer. If the outer stream fires ten times and no code tracks the ten inner subscriptions, ten resources are open at once and none of them is being cancelled when the outer moves on. Flatteners are subscription managers. The policy they apply to that management is the entire subject of this chapter.

The concurrency policy. Flattening operators are not just plumbing. Each one encodes a business rule about concurrency. switchMap says “only the latest matters.” mergeMap says “I want all of them, in parallel.” concatMap says “in order, one at a time.” exhaustMap says “one at a time, and new requests are invalid while one is in flight.” Those are product decisions, and the operator name is the decision written in code.

The race condition. The classic bug in frontend code is the stale response โ€” user types a, then ab, and the response for a arrives after the response for ab. With two independent fetch calls, nothing prevents the older one from overwriting the newer. switchMap fixes this in one word by unsubscribing a‘s inner observable the moment ab is emitted, so the response for a is never delivered. Every other flattener leaves that race in place on purpose.

The backpressure problem. A source that emits faster than the consumer can handle is a source with backpressure. mergeMap in particular will happily start a hundred concurrent HTTP requests and stall the browser’s six-connection-per-origin limit. mergeMap with a concurrency argument caps running inners and queues the rest, which is the fix. concatMap is the same operator with concurrency permanently set to 1. The distinction between backpressure and cancellation is exactly the choice between mergeMap and switchMap.

The latency trade-off. switchMap gives the freshest result but drops work that was already in flight; a cancelled POST may still reach the server. concatMap guarantees every value is processed but the last one may take a long time behind the queue. exhaustMap guarantees no duplicate concurrent work but silently discards clicks. All four are defensible; none is correct in every context. The rule is that the operator must match the business semantics of the operation, not its speed.


a. The nested-observable problem

An outer observable emits values. When a mapping function turns each value into an observable, the result is Observable<Observable<T>> โ€” a stream of streams. Subscribing to it does not subscribe to the inner streams; nothing in RxJS does that implicitly. map in RxJS is not flatMap in any language โ€” it never unwraps.

import { of, map, Observable } from 'rxjs';

const ids$ = of(1, 2, 3);

// Each id is mapped to an Observable, so the result is a nested
// observable. Subscribing to it does not subscribe to the inner ones.
const nested$: Observable<Observable<string>> = ids$.pipe(
  map((id) => fetchUser(id))       // Observable<string> per id
);

nested$.subscribe((inner: Observable<string>) => {
  // `inner` is not a user, it is an observable that has never been run
  console.log(inner);              // Observable<string> object
});

The fix is a flattening operator. mergeAll, switchAll, concatAll, and exhaustAll are the generic forms that take no projection function โ€” they subscribe to the inner observables themselves. The four named operators in this chapter (mergeMap, switchMap, concatMap, exhaustMap) are the combination of map and the corresponding *All.

import { of, mergeMap, delay } from 'rxjs';

// `mergeMap` = `map` + `mergeAll`: subscribe to every inner observable
of(1, 2, 3)
  .pipe(mergeMap((id) => fetchUser(id)))
  .subscribe((user) => {
    // `user` is a real string, not an Observable
    console.log(user);
  });

Once the mental model is Observable<Observable<T>> collapsed into Observable<T>, each operator becomes trivial to distinguish. They all collapse; they disagree only on the policy they apply to the inner subscriptions during the collapse.


b. switchMap โ€” cancel the previous inner observable

switchMap(project) calls project for every outer value, subscribes to the returned inner observable, and โ€” critically โ€” unsubscribes from any previous inner observable that is still active. The name is descriptive: the operator switches to the newest inner. The outer values that arrive later do not queue; they replace.

import { fromEvent, map, debounceTime, switchMap } from 'rxjs';
import { HttpClient } from '@angular/common/http';

const searchEl = document.querySelector<HTMLInputElement>('#search')!;
const http = new HttpClient();

fromEvent(searchEl, 'input')
  .pipe(
    // 1. Read the current text from the event
    map(() => searchEl.value.trim()),
    // 2. Wait for typing to settle before firing a request
    debounceTime(300),
    // 3. Cancel the previous HTTP request if a new term arrives
    switchMap((term) =>
      term.length < 2
        ? of([])                                // short term: no request
        : http.get(`/api/search?q=${encodeURIComponent(term)}`)
    )
  )
  .subscribe((results) => renderResults(results));

The three cases switchMap guarantees are worth memorising because they cover 90% of the operator’s behaviour.

A new outer value cancels the running inner. If the user types rx, then rxjs before the rx request completes, the rx request is unsubscribed. The browser will abort the in-flight XHR if the underlying observable supports it (Angular’s HttpClient does). If the response was already in transit, switchMap has dropped the delivery slot and the callback will not fire.

An outer value that produces an inner error terminates the whole pipeline. switchMap does not catch; it propagates. If the rxjs request fails, the outer stream dies. Wrap the inner with catchError to keep the outer alive.

The outer completes before the inner. When the outer source completes, switchMap waits for the currently running inner to finish, then completes. It does not abandon the in-flight work. This is what makes switchMap safe at the end of a finite source.

The classic mistake with switchMap is using it for writes. A cancel is a lost write. A user pressing “save” once per keystroke, with each save modelled as switchMap, will cancel eight of the nine saves it started. That is not the operator’s fault; it is the wrong operator for the shape of the work.

import { Subject, switchMap, catchError, of } from 'rxjs';

// WRONG: a save can be cancelled by a later save
const save$ = new Subject<{ id: number; body: string }>();

save$
  .pipe(
    switchMap((payload) => http.put(`/items/${payload.id}`, payload.body)),
    catchError((err) => {
      showError(err);
      return of(null);                // keep the outer stream alive
    })
  )
  .subscribe();

switchMap is the operator for read-side work where the latest result is the only one that matters โ€” search, autocomplete, route parameters, dependent fetches whose previous results are stale on arrival.


c. mergeMap โ€” parallel by default, bounded on demand

mergeMap(project, concurrency?) (also exported as flatMap) subscribes to every inner observable and keeps them all running in parallel. There is no cancellation and no queueing unless a concurrency argument is supplied. Results are delivered in the order the inners emit, which is not the order the outer values arrived.

import { from, mergeMap } from 'rxjs';

const ids = [1, 2, 3, 4, 5, 6, 7, 8];

from(ids)
  .pipe(
    // All eight requests start immediately; five will queue at the
    // browser connection limit, and the responses arrive out of order
    mergeMap((id) => fetchUser(id))
  )
  .subscribe((user) => {
    // Order of `user` is the network order, not the input order
    console.log(user);
  });

The parallel default is the reason mergeMap is dangerous. Every outer value causes a subscription, and every subscription holds a connection or a listener. A fromEvent trigger with a mergeMap on http.get fires one request per event with no ceiling. The concurrency argument is not optional for reactive code that touches the network.

import { from, mergeMap } from 'rxjs';

from(ids)
  .pipe(
    // Cap at 3 inners running at once; the remaining values queue
    mergeMap((id) => fetchUser(id), 3)
  )
  .subscribe((user) => console.log(user));

The concurrency argument changes the operator’s behaviour to a queue once the cap is reached. The first three ids start immediately. When one completes, the next id is subscribed. The output order still follows completion order, not submission order.

There is one important asymmetry compared with switchMap. When an inner errors under mergeMap, the inner error propagates and the whole outer stream terminates. There is no automatic retry, and the other active inners are also unsubscribed. If per-inner error handling is needed, catchError must be applied inside the projection so the inner observable completes normally and the outer stays alive.

from(ids)
  .pipe(
    mergeMap((id) =>
      fetchUser(id).pipe(
        // Per-inner error handling keeps the outer stream alive
        catchError((err) => {
          logFailed(id, err);
          return of(null);            // emit a placeholder and complete
        })
      ),
      3                              // still capped at 3 concurrent
    )
  )
  .subscribe((user) => user && render(user));

mergeMap is the operator for parallel batch work where all results matter: firing the same call against an array of ids, uploading several files at once with a concurrency cap, fan-out where order is irrelevant.


d. concatMap โ€” queue and preserve order

concatMap(project) is mergeMap with concurrency fixed at 1. Only one inner observable runs at a time; every subsequent outer value is queued, and its inner is subscribed only after the previous inner completes. Output order is guaranteed to match input order.

import { from, concatMap } from 'rxjs';

from([1, 2, 3, 4])
  .pipe(
    // Requests run strictly one at a time: request 2 starts only
    // after request 1 completes, request 3 only after 2, etc.
    concatMap((id) => saveItem(id))
  )
  .subscribe((result) => {
    // Results arrive in input order: 1, 2, 3, 4
    console.log(result);
  });

concatMap is the operator for anything where order or serialisation is part of the requirement. Database writes that must apply in sequence, HTTP PUTs that must not race on the same resource, file downloads that must write to one file in order, animation steps that must play one after another. In every one of those cases, running them in parallel produces a wrong result, and cancel-on-new produces a lost write; serialisation is the only correct answer.

The cost is latency. Total time is the sum of every inner’s duration. A concatMap over four 500 ms requests takes 2 s wall clock; a mergeMap over the same four takes roughly 500 ms if the browser runs them all. concatMap is slow by design because it never overlaps. That cost is the price of the ordering guarantee.

import { fromEvent, concatMap } from 'rxjs';

const saveBtn = document.querySelector<HTMLButtonElement>('#save')!;

fromEvent(saveBtn, 'click')
  .pipe(
    // Each click is a save; every save completes before the next starts
    // Even rapid clicking cannot interleave two PUTs on the same row
    concatMap(() => http.put('/api/draft', readEditor()))
  )
  .subscribe((res) => showSaved(res));

concatMap does not drop clicks; it queues them. A user clicking “save” ten times in one second will cause ten sequential PUTs. That is usually the wrong product behaviour โ€” exhaustMap is the operator for that case. concatMap is correct when the work must happen, all of it, in order.

Errors under concatMap behave like mergeMap: an error inside an inner terminates the outer stream and discards the queue. catchError inside the projection is again the way to keep the outer alive and continue to the next value.


e. exhaustMap โ€” ignore outer values while busy

exhaustMap(project) subscribes to an inner observable for the first outer value; then, while that inner is still running, it silently ignores every new outer value. When the inner completes, the operator becomes receptive again. The name comes from the metaphor of exhausting capacity โ€” the operator stays unresponsive until its single slot is free.

import { fromEvent, exhaustMap } from 'rxjs';

const loginBtn = document.querySelector<HTMLButtonElement>('#login')!;

fromEvent(loginBtn, 'click')
  .pipe(
    // The first click triggers the login request; every click that
    // arrives while the request is running is dropped entirely
    exhaustMap(() => http.post('/api/login', readForm()))
  )
  .subscribe((session) => redirect('/dashboard'));

The behaviour is exactly what a form submit button needs. Rapid double-clicks do not fire two logins, do not queue two logins, and do not cancel the first login โ€” they produce nothing at all. The user sees one request and one outcome. Compare with the alternatives: switchMap would cancel the first login when the second click arrives, so a slow login could be cancelled by an impatient double-click; concatMap would queue a second login and hit the server twice; mergeMap would fire two logins in parallel and produce two sessions.

exhaustMap is the right choice when the action is non-idempotent and must not run concurrently with itself. Login, form submit, refresh button, payment charge, file upload triggered from a UI button. All of them share the property that “running once is correct, running twice is a bug, and cancelling a running one is also a bug.” exhaustMap is the only one of the four that satisfies all three at once.

The trade-off is that user intent can be silently dropped. A refresh button with a 10 s upstream latency and exhaustMap will ignore nine of ten clicks. That is usually acceptable because the intent of the tenth click is identical to the first; the first is already in flight. But it is not acceptable if the button carries different data on each click (a column-sort header, for example). In that case switchMap is the correct operator because the last click is the one the user wants.

Errors under exhaustMap behave like the other three: an inner error terminates the outer. And unlike debounceTime-style operators there is nothing to flush on completion โ€” any outer value that was ignored while an inner was running is gone, not queued. That is the entire point.


f. The related operators and the decision rule

The *All variants are the lower-level forms and are worth knowing because they separate mapping from flattening. switchAll, mergeAll, concatAll, and exhaustAll take a source that is already Observable<Observable<T>> and apply the same policy without a projection function.

import { of, timer, switchAll, map } from 'rxjs';

const nested$ = of(1, 2, 3).pipe(
  map((n) => timer(n * 100))          // Observable<number> per input
);

nested$
  .pipe(
    // switchAll subscribes to the inner observable and cancels the
    // previous one whenever a new inner arrives
    switchAll()
  )
  .subscribe((v) => console.log(v));

The decision rule compresses to one question: when a new outer value arrives while an inner is still running, what should happen to that inner?

If the answer is “cancel it” โ€” switchMap. If “keep it and start a new one” โ€” mergeMap (with a concurrency cap if that is not safe). If “finish it first, then start the new one” โ€” concatMap. If “drop the new outer value entirely” โ€” exhaustMap. Those are the four possible answers and therefore the four operators. Anything else is one of the four composed with another operator.

There is one adjacent family worth naming for completeness. forkJoin runs a fixed set of inners in parallel and emits their final values once, which is the RxJS equivalent of Promise.all. combineLatest emits every time one of several sources changes. Those are combinators, not flatteners, but they belong in the same mental toolbox because they answer the same family of “how do I coordinate multiple async sources” questions that the four flatteners answer piecewise.


Complete Example Session

// ============================================
// PART 1: IMPORTS AND HELPERS
// ============================================
import { from, fromEvent, of, Subject, timer } from 'rxjs';
import {
  map, switchMap, mergeMap, concatMap, exhaustMap,
  catchError, delay, tap, finalize
} from 'rxjs/operators';

const searchEl = document.querySelector<HTMLInputElement>('#search')!;
const saveBtn  = document.querySelector<HTMLButtonElement>('#save')!;
const loginBtn = document.querySelector<HTMLButtonElement>('#login')!;

// ============================================
// PART 2: SEARCH โ€” switchMap CANCELLS THE OLD REQUEST
// ============================================
fromEvent(searchEl, 'input')
  .pipe(
    map(() => searchEl.value.trim()),
    switchMap((term) =>
      term.length < 2
        ? of([])
        : http.get(`/api/search?q=${encodeURIComponent(term)}`).pipe(
            // If the request is aborted by a newer term, the error
            // is swallowed so the outer stream keeps running
            catchError(() => of([]))
          )
    )
  )
  .subscribe((results) => renderSuggestions(results));

// ============================================
// PART 3: SAVE โ€” concatMap QUEUES WRITES IN ORDER
// ============================================
fromEvent(saveBtn, 'click')
  .pipe(
    // Rapid clicks must all be processed, one at a time, in order.
    // The last save wins because it lands last, not because earlier
    // saves were dropped.
    concatMap(() =>
      http.put('/api/draft', readEditor()).pipe(
        finalize(() => saveBtn.disabled = false)
      )
    )
  )
  .subscribe((res) => showSavedBanner(res.updatedAt));

// ============================================
// PART 4: PARALLEL UPLOAD โ€” mergeMap WITH A CAP
// ============================================
const selectedFiles: File[] = await pickFiles();

from(selectedFiles)
  .pipe(
    // Fire at most 3 uploads at once; the rest queue
    mergeMap((file) => uploadFile(file), 3)
  )
  .subscribe({
    next: (result) => progress.update(result),
    error: (err)   => console.error('upload failed', err)
  });

// ============================================
// PART 5: LOGIN โ€” exhaustMap IGNORES EXTRA CLICKS
// ============================================
fromEvent(loginBtn, 'click')
  .pipe(
    // Only the first click in each window opens a request;
    // every other click while it is running is dropped
    exhaustMap(() =>
      http.post('/api/login', readForm()).pipe(
        catchError((err) => {
          showError(err);
          return of(null);
        })
      )
    )
  )
  .subscribe((session) => session && redirect('/dashboard'));

// ============================================
// PART 6: POST-COMPLETION ORDER โ€” switchMap ON ROUTE PARAMS
// ============================================
const routeParams$ = new Subject<{ userId: number }>();

routeParams$
  .pipe(
    // Whenever the route changes, cancel the previous user load;
    // the newest route is the only one the user wants to see
    switchMap(({ userId }) =>
      http.get<User>(`/api/users/${userId}`).pipe(
        catchError((err) => of<User | null>(null))
      )
    )
  )
  .subscribe((user) => renderProfile(user));

// ============================================
// PART 7: SIDE BY SIDE ON ONE SOURCE
// ============================================
// A source that emits 1, 2, 3 at 50ms intervals, then completes
const source$ = from([1, 2, 3]).pipe(
  map((n, i) => i * 50),
  // turn the timing into observable delays so the demo is stable
);

// Four subscribers to four flatteners on the same dense source
source$.pipe(switchMap((n) => runOp(n))).subscribe((v) =>
  console.log('switch ', v)
);
source$.pipe(mergeMap((n) => runOp(n))).subscribe((v) =>
  console.log('merge  ', v)
);
source$.pipe(concatMap((n) => runOp(n))).subscribe((v) =>
  console.log('concat ', v)
);
source$.pipe(exhaustMap((n) => runOp(n))).subscribe((v) =>
  console.log('exhaust', v)
);

// Observed output (documented for teaching; runOp is 40ms):
//   switch  3      <- 1 and 2 cancelled mid-flight, 3 wins
//   merge   2, 1, 3 <- all fire; results in completion order
//   concat  1, 2, 3 <- serialised; total time 3 x 40ms
//   exhaust 1      <- 2 and 3 dropped while op 1 was running

// ============================================
// PART 8: THE CONFIGURATION MATRIX
// ============================================
// No runtime config; the operators are chosen by intent.
//
// READ side (last result wins)        -> switchMap
// WRITE side (all must apply in order)-> concatMap
// BATCH side (all run in parallel)    -> mergeMap(n)
// ACTION side (never run twice)       -> exhaustMap
//
// Under any of them, an inner error terminates the outer
// stream unless catchError is applied inside the projection.

// ============================================
// PART 9: A DIRECT COMPARISON ON CLICK EVENTS
// ============================================
const clicks$ = fromEvent(document, 'click');

// The first click opens a 1000ms inner; the next click arrives before
// it completes, which is exactly the scenario each operator handles
// differently.
clicks$.pipe(
  switchMap(() => timer(1000).pipe(map(() => 'switch done'))),
  tap((msg) => console.log(msg))
).subscribe();

clicks$.pipe(
  exhaustMap(() => timer(1000).pipe(map(() => 'exhaust done'))),
  tap((msg) => console.log(msg))
).subscribe();

// Rapid double click:
//   switch  -> only 'switch done' for the second click (first cancelled)
//   exhaust -> only 'exhaust done' for the first click (second ignored)

// ============================================
// PART 10: THE ASSEMBLED PIPELINE
// ============================================
const term$ = fromEvent(searchEl, 'input').pipe(
  map(() => searchEl.value.trim())
);

const searchResults$ = term$.pipe(
  switchMap((term) =>
    term.length < 2
      ? of([])
      : http.get<Result[]>(`/api/search?q=${term}`)
  )
);

const save$ = fromEvent(saveBtn, 'click').pipe(
  concatMap(() => http.put('/api/draft', readEditor()))
);

const login$ = fromEvent(loginBtn, 'click').pipe(
  exhaustMap(() => http.post('/api/login', readForm()))
);

const upload$ = from(selectedFiles).pipe(
  mergeMap((file) => uploadFile(file), 3)
);

The ten parts built a search box with switchMap, an ordered save with concatMap, a capped parallel upload with mergeMap, a login with exhaustMap, route-parameter loading with switchMap, a side-by-side comparison on one source, the configuration matrix, a direct comparison on click events, and finally an assembled pipeline that uses all four operators on their correct sides of the read/write/action split.


Quick Reference

The Four Operators

OperatorPrevious inner when new arrivesOrderCancel-safe
switchMapcancelledlatest onlyloses writes
mergeMapkept, runs in parallelcompletion orderfloods on rapid input
concatMapkept, new queuesinput orderslow = latency
exhaustMapkept, new is ignoredfirst-onlydrops later clicks

When to Use Which

ScenarioOperator
SearchswitchMap
Route param loadswitchMap
Save draft on clickconcatMap
Send batch of idsmergeMap(ids, n)
Login buttonexhaustMap
Form submitexhaustMap
Upload N filesmergeMap(files, 3)
Sequential database writesconcatMap

The *All Forms

CombinedBare
switchMapswitchAll
mergeMap / flatMapmergeAll
concatMapconcatAll
exhaustMapexhaustAll

Error Behaviour

Point of errorEffect on outer
Inside projectterminates outer unless catchError
Inside inner, catchError appliedouter survives
Outer source errorouter terminates, inner cancelled

Best Practices

โœ… Do This:

// Read side: cancel the old request when a new term arrives
term$.pipe(switchMap((t) => http.get('/s?q=' + t)));             // โœ…

// Write side: queue every write so none is dropped
click$.pipe(concatMap(() => http.put('/draft', body)));          // โœ…

// Batch side: cap the parallel work
from(ids).pipe(mergeMap((id) => fetchUser(id), 4));              // โœ…

// Non-idempotent action: never run twice at once
click$.pipe(exhaustMap(() => http.post('/login', form)));        // โœ…

// Keep the outer stream alive when one inner fails
term$.pipe(switchMap((t) => http.get(...).pipe(catchError(() => of([]))))); // โœ…

// Use the null-return idiom to swallow per-inner errors
mergeMap((id) => fetchUser(id).pipe(catchError(() => of(null))));// โœ…

โŒ Don’t Do This:

// Save on a switchMap: each click may cancel the previous PUT
click$.pipe(switchMap(() => http.put('/draft', body)));          // โŒ

// mergeMap without a cap: one request per event, unbounded
events$.pipe(mergeMap((e) => http.get('/x')));                   // โŒ

// concatMap for a fast-refresh button: queues every click
click$.pipe(concatMap(() => reload()));                          // โŒ

// exhaustMap on a context that requires every click to count
submit$.pipe(exhaustMap((row) => saveRow(row)));                 // โŒ

// Forgetting to catch per-inner errors: one failure kills the stream
term$.pipe(switchMap((t) => http.get('/s?q=' + t)));             // โŒ

// Nested subscribe for an inner observable
ids$.subscribe((id) => http.get('/u/' + id).subscribe(render));   // โŒ

Common Pitfalls

PitfallWhy It HappensFix
Second click cancels first saveswitchMap used for a writeswap to concatMap
Double POST on double clickmergeMap used on a formswap to exhaustMap
Requests fire past the browser limitmergeMap with no concurrencyadd , 4
Route change shows old user datamergeMap used for route loadingswap to switchMap
User intent silently droppedexhaustMap on a varying payloadswap to switchMap
Outer stream dies on first 404no catchError inside projectwrap inner with catchError
Results out of input ordermergeMap used for ordered workswap to concatMap
Memory leak on unmountsubscription not trackedtakeUntil(destroy$)

Real-World Examples

1. Search autocomplete

term$.pipe(debounceTime(300), switchMap((q) => http.get('/s?q=' + q)));

2. Save draft on click

click$.pipe(concatMap(() => http.put('/draft', readEditor())));

3. Login button

login$.pipe(exhaustMap(() => http.post('/login', readForm())));

4. Route param load

id$.pipe(switchMap((id) => http.get('/users/' + id)));

5. Parallel batch fetch

from(ids).pipe(mergeMap((id) => fetchUser(id), 4));

6. File upload

from(files).pipe(mergeMap((f) => upload(f), 3));

7. Sequential animation

from(steps).pipe(concatMap((s) => playStep(s)));

8. Timed refresh

interval(30_000).pipe(switchMap(() => http.get('/status')));

9. Type-ahead with null fallback

term$.pipe(switchMap((q) => http.get('/s').pipe(catchError(() => of([])))));

10. Refresh button throttle

refresh$.pipe(exhaustMap(() => http.get('/data')));

Visual

The Four Inner-Subscription Policies

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ THE FOUR INNER-SUBSCRIPTION POLICIES                 โ”‚
โ”‚                                                      โ”‚
โ”‚ switchMap   cancel previous, subscribe to new        โ”‚
โ”‚ mergeMap    keep previous, subscribe to new          โ”‚
โ”‚ concatMap   queue new, subscribe when previous done  โ”‚
โ”‚ exhaustMap  ignore new while previous is active      โ”‚
โ”‚                                                      โ”‚
โ”‚ all four map outer values to inner observables;      โ”‚
โ”‚ they differ only in what happens to the inner        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

switchMap Timeline

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ switchMap: a new outer value CANCELS the inner       โ”‚
โ”‚                                                      โ”‚
โ”‚ outer   a        b            c                      โ”‚
โ”‚         โ”‚        โ”‚            โ”‚                      โ”‚
โ”‚ inner   a--x     b--y         c--z                   โ”‚
โ”‚         ^        ^            ^                      โ”‚
โ”‚         โ”‚        โ”‚            โ”‚                      โ”‚
โ”‚         cancel   cancel       completes              โ”‚
โ”‚                                                      โ”‚
โ”‚ only the last inner completes;                       โ”‚
โ”‚ all earlier inners are unsubscribed mid-flight       โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

mergeMap With a Concurrency Cap

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ mergeMap: overlap inners, optionally limited         โ”‚
โ”‚                                                      โ”‚
โ”‚ outer  a     b     c     d     e                     โ”‚
โ”‚                                                      โ”‚
โ”‚ merge  [a--]                                         โ”‚
โ”‚        [b------]                                     โ”‚
โ”‚          [c--]                                       โ”‚
โ”‚                 [d-------]                           โ”‚
โ”‚                       [e----]                        โ”‚
โ”‚                                                      โ”‚
โ”‚ concurrency:2 means only two inners run at once;     โ”‚
โ”‚ the rest wait in a queue, like concatMap             โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

concatMap Preserves Strict Order

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ concatMap: preserve order, one inner at a time       โ”‚
โ”‚                                                      โ”‚
โ”‚ outer   a     b     c     d                          โ”‚
โ”‚                                                      โ”‚
โ”‚ inner  [a--]                                         โ”‚
โ”‚              [b------]                               โ”‚
โ”‚                        [c--]                         โ”‚
โ”‚                              [d-------]              โ”‚
โ”‚                                                      โ”‚
โ”‚ 'b' is not subscribed until 'a' completes;           โ”‚
โ”‚ 'c' waits for 'b', 'd' waits for 'c'                 โ”‚
โ”‚ total time = sum of all inner durations              โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

exhaustMap Drops While Busy

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚ exhaustMap: ignore outer values while inner active   โ”‚
โ”‚                                                      โ”‚
โ”‚ outer   a  b  c     d  e  f                          โ”‚
โ”‚         โ”‚  โ”‚  โ”‚     โ”‚  โ”‚  โ”‚                          โ”‚
โ”‚ inner  [a------]   [d------]                         โ”‚
โ”‚                                                      โ”‚
โ”‚ b and c arrive while 'a' is running  ->  dropped     โ”‚
โ”‚ e and f arrive while 'd' is running  ->  dropped     โ”‚
โ”‚                                                      โ”‚
โ”‚ use when the action must not run twice; for example  โ”‚
โ”‚ a submit button that must not double-post            โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Summary

ItemValue
switchMapcancel previous inner, subscribe new
mergeMap / flatMapkeep all inners, running in parallel
concatMapone at a time, queue the rest
exhaustMapignore new while an inner is active
Optional concurrencymergeMap(fn, n) caps parallel inners
concatMap equivalencemergeMap(fn, 1)
Error propagationterminates outer unless catchError inside projection
Order of resultsswitchMap/mergeMap = completion order, concatMap = input order
Cancellation of in-flightswitchMap and completion of outer only
Typical readswitchMap
Typical writeconcatMap
Typical actionexhaustMap
Typical batchmergeMap(n)

Key takeaways:

  • switchMap cancels the previous inner. It is the operator for read-side work where only the latest result matters โ€” search, autocomplete, route parameters. It is the wrong operator for any write, because a cancel is a lost write.
  • mergeMap runs all inners in parallel. Without a concurrency argument it is dangerous on event-driven sources because it starts one inner per event, unbounded. Add mergeMap(fn, n) to cap and queue.
  • concatMap is mergeMap(fn, 1). It preserves input order at the cost of latency. Total time is the sum of every inner’s duration. It is correct when order or serialisation is a requirement, and wrong for a button that should not queue.
  • exhaustMap ignores new outer values while busy. It is the operator for non-idempotent actions that must never run twice concurrently, and never cancel an in-flight one. Login, form submit, refresh.
  • All four terminate the outer stream on an inner error. catchError must be applied inside the projection to keep the outer alive. The of([]) and of(null) fallbacks are the two idiomatic patterns.
  • The decision rule is one question. When a new outer value arrives and an inner is still running, should the previous inner be cancelled, kept, finished first, or should the new outer value be dropped? Cancel -> switchMap. Keep -> mergeMap(n). Finish first -> concatMap. Drop new -> exhaustMap.
  • The policy is a product decision, not a performance decision. The operator name is the business rule written in code. It should match the semantics of the operation โ€” a save is a concatMap, a login is exhaustMap, a search is switchMap, a batch fetch is mergeMap with a cap.

Remember: A higher-order observable is Observable<Observable<T>>, and flattening collapses it to Observable<T>; the four flatteners differ only by the inner-subscription policy they apply during that collapse. switchMap cancels the previous inner to keep only the latest work alive; mergeMap keeps every inner in parallel and lets a concurrency cap tame that; concatMap queues every inner so order is preserved; exhaustMap ignores new outer values so no concurrent execution is possible. Pick the operator by matching its policy to whether the previous inner should be cancelled, kept, finished, or replaced with nothing โ€” and wrap the inner with catchError so one failure does not tear down the outer stream.

Was this helpful?


Stop using slow, ad-bloated tool sites! ๐Ÿคฎ

๐Ÿ”Ž Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
โœ… Finance (Mortgage, Interest, Inflation)
โœ… Tech (Base64, JSON, Dev Suite, IP)
โœ… Health (BMI, BMR, TDEE)
โœ… Productivity (Timer, Workspace, QR)

โšก๏ธ Fast & Private
๐Ÿ”’ No data leaves your device
๐Ÿ’Ž 100% Free

๐Ÿ”— Use it now: https://tools.kandz.me
๐Ÿ”– Bookmark itโ€”youโ€™ll need it later!