Are you learning RxJS, preparing for Angular job interviews, or struggling to understand the key differences between these three critical operators?
Let’s break down concatMap, mergeMap, and switchMap. While they all "flatten" Observables, their behavior is quite different and choosing the wrong one can lead to subtle bugs.
To make them easier to grasp, let’s use a job interview analogy with Google and Microsoft.
Scenario: The Interview Process
Imagine you're interviewing at this two companies:
- First Observable (hrInterviews$) → The HR interview (happens first).
const hrInterviews$ = of('GoogleHRInterview', 'MicrosoftHRInterview')
- Second Observable (pmInterview) → The Product Manager interview (happens after HR).
We'll see how each operator changes the flow of these interviews.
1. concatMap: Finish One Interview Before Starting the Next
Runs Observables in sequence. When order matters (e.g., sequential API calls).
Analogy:
- You finish Google’s HR interview → Start Google’s PM interview.
- Only after Google’s PM interview is done, you move to Microsoft’s HR interview, then its PM interview.
hrInterviews$.pipe(
concatMap(company => pmInterview(company))
).subscribe();
Output: Google HR → Google PM → Microsoft HR → Microsoft PM
2. mergeMap: Run All Interviews in Parallel
Runs Observables in parallel. When tasks are independent (e.g., multiple API calls).
Analogy:
- You finish Google’s HR interview → Start Google’s PM interview.
- At the same time, if Microsoft’s HR interview finishes, you immediately start Microsoft’s PM interview.
hrInterviews$.pipe(
mergeMap(company => pmInterview(company))
).subscribe();
Output (possible interleaving): Google HR → Microsoft HR → Google PM → Microsoft PM
3. switchMap: Cancel Previous Interview If a New One Starts
Cancels the previous Observable when a new one arrives. When only the latest matters (e.g., search autocomplete).
Analogy:
- You finish Google’s HR interview → Start Google’s PM interview.
- But if Microsoft’s HR interview finishes before Google’s PM interview ends, you cancel Google’s PM interview and switch to Microsoft’s PM interview.
hrInterviews$.pipe(
switchMap(company => pmInterview(company))
).subscribe();
Output (if Microsoft HR arrives before Google PM finishes): (Google PM starts) → Microsoft HR → (Google PM cancelled) → Microsoft PM
Wrapping up
-
Need strict order? →
concatMap
-
Need parallel execution? →
mergeMap
-
Only care about the latest? →
switchMap
Try your RxJS code online at playcode.io/rxjs.
Top comments (0)