Skip to main content

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:

  1. takes a value from the source Observable
  2. creates an inner Observable
  3. subscribes to all inner Observables at once
  4. merges their results

Signature:

ts
source$.pipe( mergeMap(value => observable$) )

Example

ts
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 3

They 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:

ts
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:

ts
mergeMap(fn, 3)

No more than 3 active Observables at a time.

Difference from the other map operators

OperatorBehavior
switchMapcancels the previous one
concatMapone after another
mergeMapin parallel
exhaustMapignores 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 ready
Premium

A concise answer to help you respond confidently on this topic during an interview.