RxJS & Reactive Programming
Angular switchMap mergeMap concatMap
These flattening operators handle an inner Observable created per emitted value. They differ in what happens when a new value arrives while a previous inner Observable is still running.
What is switchMap mergeMap concatMap in Angular?
These flattening operators handle an inner Observable created per emitted value. They differ in what happens when a new value arrives while a previous inner Observable is still running.
switchMap mergeMap concatMap example
this.searchControl.valueChanges.pipe(
debounceTime(400),
distinctUntilChanged(),
switchMap(term => this.api.search(term)) // cancels the stale request
).subscribe(results => (this.results = results));How this works
Each keystroke that survives the debounce cancels the previous in-flight request, so results can never arrive out of order. Using mergeMap here would let a slow earlier response overwrite a newer one.
Key points to remember
- switchMap is the right default for anything driven by user input or route changes.
- exhaustMap on a login button prevents duplicate submissions.
- These operators replace nested subscribe calls entirely.
Choosing a flattening operator
| Operator | Behaviour | Use for |
|---|---|---|
| switchMap | cancels the previous inner Observable | search-as-you-type, route param changes |
| mergeMap | runs all inner Observables concurrently | independent parallel requests |
| concatMap | queues them, one at a time in order | ordered writes, sequential saves |
| exhaustMap | ignores new values while one is running | preventing double form submits |
Common mistakes with switchMap mergeMap concatMap
- Using switchMap for a POST that must not be cancelled halfway.
- Nesting subscribe inside subscribe instead of flattening.
Angular switchMap mergeMap concatMap— Interview Questions & FAQs
When should I use switchMap instead of mergeMap?+
When only the latest result matters — search boxes, route parameter changes, filter updates. switchMap cancels the previous request; mergeMap would let an older, slower response arrive last and overwrite the newer one.
