Skip to the page

RxJS · core

switchMap, mergeMap, concatMap, exhaustMap and the typeahead

The four operators map each value to an inner Observable. They differ in what happens when a new value arrives while the old inner one still runs.

The notes

What you must know

  • switchMap: unsubscribes the previous inner Observable (cancels the HTTP call). The latest wins. Use for search, typeahead, route params.
  • mergeMap: runs all inner Observables at the same time. Results may arrive out of order.
  • concatMap: runs one at a time, in order. Use when order matters, such as saving edits in sequence.
  • exhaustMap: ignores new values while one inner is running. Use for submit buttons and polling.
  • Typeahead pipe: map(trim), debounceTime(300), distinctUntilChanged(), then switchMap.
  • For short queries, switch to an empty result (of(EMPTY)) rather than filter, so old results do not stay on screen.
  • Inside the inner Observable use startWith(loading) and catchError so the outer stream stays alive.

The red pen

Common traps: mistake → fix

  • Mistake: switchMap is always right for saving data

    Fix: it can cancel a save in flight; use concatMap or exhaustMap.

  • Mistake: mergeMap keeps the order of results

    Fix: it does not.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is the difference between switchMap and mergeMap?
  2. Which operator for a double-click-safe submit button?
  3. Build a debounced search.
  4. Which operator for saving edits that must keep order?

Practise

Practise with these questions

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview