When to use Rxjs mergeMap



  1. flatMap is an alias for mergeMap.
  2. If only one inner subscription can be active at a time, use switchMap.
  3. If the order of emission and subscription of inner observables matters, use concatMap.

MergeMap is an excellent use case when you need to flatten the inner observable but want to manually control the number of inner subscriptions.

For example, when using switchMap, each inner subscription is done when the source emits, ie only one active inner subscription is allowed at any time period. In contrast, mergeMap allows multiple inner subscriptions to be active at the same time. Therefore, one of the most common use cases for mergeMap are requests that should not be canceled, which are considered writes rather than reads.

A typical example is the amount of different line items in the SAP e-commerce cloud shopping cart, which can be increased or decreased in parallel.

Note that concatMap is a better choice if these writes must be kept in order. Such as database write operations.

Since mergeMap maintains multiple active internal subscriptions at a time, it may cause memory leaks due to long-lived internal subscriptions. A basic example is if you use internal timers or dom event streams mapped to observables. In these cases, if you still wish to use mergeMap, a good idea is to utilize another operator to manage the completion of the inner subscription, eg consider take or takeUntil. Of course, you can also use the concurrent parameter to limit the number of internal subscriptions at one time.

See an example:

import { fromEvent, of } from 'rxjs';
import { mergeMap, delay } from 'rxjs/operators';

// faking network request for save
const saveLocation = location => {
  return of(location).pipe(delay(500));
// streams
const click$ = fromEvent(document, 'click');

    mergeMap((e: MouseEvent) => {
      return saveLocation({
        x: e.clientX,
        y: e.clientY,
        timestamp: Date.now()
  // Saved! {x: 98, y: 170, ...}
  .subscribe(r => console.log('Saved!', r));

saveLocation is a function that wraps any incoming input parameters into an Observable, and this Observable does not emit data immediately, but delays 500 milliseconds.

When to use Rxjs mergeMap

mergeMap receives a function as an input parameter. The input parameter of this function is the element contained in the Observable linked to mergeMap through pipe, that is, MouseEvent; the data type returned by project is a new Observable, which contains the X and Y coordinates of the screen click and the current timestamp.

When to use Rxjs mergeMap

The final output produced:
When to use Rxjs mergeMap

When to use Rxjs mergeMap