MyInternships.in

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

The canonical search pipeline
TypeScript
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

OperatorBehaviourUse for
switchMapcancels the previous inner Observablesearch-as-you-type, route param changes
mergeMapruns all inner Observables concurrentlyindependent parallel requests
concatMapqueues them, one at a time in orderordered writes, sequential saves
exhaustMapignores new values while one is runningpreventing 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.

Related Angular Topics

Keep learning with these closely related lessons.

Ready to use your Angular skills?

Find verified Angular internships and fresher developer jobs across India.

Browse Angular Internships