Skip to solution
hardFrontend

What is the difference between switchMap, mergeMap, concatMap, and exhaustMap?

487 views
01

Understand the problem

Compare RxJS flattening operators.

rxjsoperators
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

All flatten inner observables but handle concurrency differently: switchMap cancels the previous inner (great for typeahead), mergeMap runs all concurrently, concatMap queues them in order, and exhaustMap ignores new emissions while one is active (great for preventing double-submits).

Solution ready — 2 min read

Classified // press E to declassify

04

Read the code

switchMap for a search box
import { fromEvent, switchMap, debounceTime, map } from 'rxjs';
// import { ajax } from 'rxjs/ajax';  // (illustrative)

const input = document.querySelector('input')!;

const results$ = fromEvent(input, 'input').pipe(
  map((e: any) => e.target.value),
  debounceTime(300),
  // cancel the previous request when a new keystroke arrives
  switchMap(term => fetch('/search?q=' + term).then(r => r.json())),
);

results$.subscribe(r => console.log('latest results only:', r));
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 101 of 121 decoded in the Angular track. One more won't hurt.

Back to track