What does mergeMap actually emit?

07 JUNE 2022
RX.JSREAL-TIME
What does mergeMap actually emit?

It actually emits the flattened inner observables that it creates for its source inputs. It is a bit of mouthful, so let's dissect it in this blog.

Essentials:

When the source stream emits an item, mergeMap processes the item with its project function. The project function takes the item, runs its logic and it must return an observable as its output. As project function does this for each item that comes through the source, we get an observable output for each item; so it's as many observables as the items that come through. mergeMap flattens the output of inner observables and returns a single observable; it, internally, does that by subscribing to each inner observable and emitting their output.

In short, mergeMap first maps the source items to inner observables, then merges the emission of those observables to return a flattened observable.

Let's look at it through an example in the Rxjs mergeMap documentation:

import { of, mergeMap, interval, map } from 'rxjs';

const letters = of('a', 'b', 'c');
const result = letters.pipe(
  mergeMap(x => interval(1000).pipe(map(i => x + i)))
);

result.subscribe(x => console.log(x));

// Results in the following:
// a0
// b0
// c0
// a1
// b1
// c1
// continues to list a, b, c every second with respective ascending integers

Our source is a letters stream; it emits one letter at a time. When it emits 'a', mergeMap projects it to an inner observable of interval(1000).pipe(map((i) => x + i)), which generates an emission every second and concatenates the given letter by x with the interval index of i. So, for the 3 letters we have in the source, we get 3 observables returned by the project function back to mergeMap.

The source completes its emission after the letter 'c' is emitted, however the 3 interval observables continue emitting every second till perpetuity. mergeMap internally subscribes to the output of each inner observable to produce a0, b0, c0, ... Finally, because mergeMap is internally subscribed to each of its project function's output observable, it receives emission from each inner observable, e.g. 'a0', 'b0', 'c0', and then emits each value into its output observable.

That's what we get at the output: flattened inner observables that the project function emits.

Near Max

© 2024 Near Max Ltd

Near Max Ltd is a limited company registered under 09222812 in England and Wales. Registered address: Highwoods, Chinnor Hill, Chinnor, Oxfordshire, OX39 4BD.

Get in touch

info@nearmax.co.uk

Highwoods, Chinnor Hill, Oxfordshire, OX39 4BD, United Kingdom