What does mergeMap do?What does mergeMap do?
In short (as in an interview)
mergeMap is an RxJS operator that subscribes to every inner Observable and runs them in parallel, merging the results into a single stream.
It cancels nothing and queues nothing.
In detail
mergeMap (also known as flatMap) is a mapping operator that:
- takes a value from the source Observable
- creates an inner Observable
- subscribes to all inner Observables at once
- merges their results
Signature:
source$.pipe(
mergeMap(value => observable$)
)Example
import { of } from 'rxjs';
import { delay, mergeMap } from 'rxjs/operators';
of(1, 2, 3).pipe(
mergeMap(v => of(v).pipe(delay(1000)))
).subscribe(console.log);Result:
1
2
3They all arrive at roughly the same time, after 1 second, because they run in parallel.
Visually
source: a----b----c
mergeMap:
inner a: -----
inner b: -----
inner c: -----
result: --- --- ---When mergeMap is used
When:
- order doesn't matter
- the operations are independent
- you need parallelism
- operations must not be canceled
Angular examples:
- sending analytics
- logging
- batch requests
- loading several resources
- background operations
For example:
from(ids).pipe(
mergeMap(id => this.api.loadUser(id))
)The loads will run in parallel.
An important nuance (frequently asked)
mergeMap can lead to:
- race conditions
- overloading the API
- subscription leaks
That's why concurrency is sometimes limited:
mergeMap(fn, 3)No more than 3 active Observables at a time.
Difference from the other map operators
| Operator | Behavior |
|---|---|
| switchMap | cancels the previous one |
| concatMap | one after another |
| mergeMap | in parallel |
| exhaustMap | ignores new ones |
This is an almost mandatory table for an Angular interview.
A typical follow-up question
This is a favorite question:
Why is mergeMap dangerous for HTTP?
Answer: because you can trigger many parallel requests, run into a data race, or overload the server.
A mini cheat sheet for the interview
You can remember it like this:
mergeMap - for independent operations concatMap - when order matters switchMap - for cancelable requests exhaustMap - to guard against repeated actions
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.