Understanding merge in RxJS

The merge operator takes multiple observable streams and emits every value produced by any of them into a single output sequence. Each time one of the combined sources delivers a value, that value immediately flows through to the result. In RxJS terminology, this behavior is commonly described as flattening.

Reach for merge when the timing or ordering of emissions across your streams doesn’t matter — when you simply want all values from several sources to appear as though they originate from one unified stream.

Here’s how the operator behaves under the hood:

  1. It subscribes to every source observable at once.
  2. Whenever any source emits a value, that value is forwarded straight to the observer.
  3. The complete notification is only sent to the observer once all source observables have completed.
  4. If any source throws an error, the error notification is immediately sent to the observer.

The following diagram illustrates merge in action with two streams, A and B, each emitting three items. As the values occur over time, they fall through into the combined result sequence:

merge operator diagram

How to use merge

merge – RxJS Reference — figure 2

Opt for this operator when emission order is irrelevant to your use case, and you care only about capturing all values from multiple combined streams as if they were a single source.

Below is a practical demonstration of applying merge across several streams:

const a = interval(500).pipe(map((v) => 'a' + v), take(3));
const b = interval(500).pipe(map((v) => 'b' + v), take(3));
merge(a, b).subscribe((value) => console.log(value));

Try it yourself

Further reading