Understanding mergeMap

The mergeMap operator is essentially a fusion of two distinct operators: merge and map. The mapping aspect allows you to transform a value coming from a source observable into an observable stream. These generated streams are commonly labeled as inner streams. Subsequently, the merge portion operates in a manner similar to mergeAll – it takes all the inner observable streams produced by the map function and merges them, emitting values concurrently from each input stream.

Whenever any of the combined sequences produce a value, that value is immediately forwarded as part of the output sequence. In technical documentation, this behavior is frequently described as flattening.

This operator is well-suited for scenarios where the sequencing of emissions is not a priority, and you only care about receiving every value from the merged streams as if they were originating from a single unified stream.

The operational flow of the operator is as follows:

  1. Initiate a subscription to the source observable.
  2. Upon receiving a new value from the source, run a map function that returns an inner observable.
  3. Subscribe to this inner observable.
  4. Forward any emissions from the inner observable directly to the observer.
  5. Send the complete notification only after every inner observable has finished.
  6. If any source observable encounters an error, propagate the error notification to the observer.

mergeMap – RxJS Reference — figure 1

Application

This operator is typically employed when you need to convert a single value into an observable. A frequent scenario involves turning URL strings into HTTP request observables.

Below is an illustration of utilizing mergeMap for this purpose:

const urls = [
   'https://api.mocki.io/v1/0350b5d5',
   'https://api.mocki.io/v1/ce5f60e2'
];

from(urls).pipe(
   mergeMap((url) => {
       return fromFetch(url);
   })
).subscribe((response) => console.log(response.status));

Interactive Example

Further Reading