Deep Dive Into The RxJs mergeMap Operator: How Does it Work?

Evelyn Taylor
2 min readDec 30, 2023

The mergeMap operator in RxJS is a powerful and commonly used operator for transforming the items emitted by an observable into other observables, and then flattening those observables into a single observable sequence. It's often referred to as a "flatMap" operator as well.

Here’s a deep dive into how mergeMap works:

Basic Syntax:

import { of } from 'rxjs';
import { mergeMap } from 'rxjs/operators';

const source = of('a', 'b', 'c');

source.pipe(
mergeMap(value => /* Observable or Promise */)
).subscribe(result => console.log(result));

How it Works:

Mapping Function:

  • For each item emitted by the source observable (source in the example), the mergeMap operator applies a mapping function.
  • The mapping function takes the current value emitted by the source observable and returns a new observable or a promise.

Flattening:

  • mergeMap then subscribes to the observable or waits for the promise to resolve.
  • If the mapping function returns an observable, mergeMap flattens it by merging its emissions into the output observable.
  • If the mapping function returns a…

--

--

Evelyn Taylor

A front-end enthusiast and dedicated development engineer, eager to expand knowledge on development techniques and collaborate with others.