Skip to content

Function: mergeMap()

mergeMap<T, R>(project): Operator<T, R>

Defined in: operators/mergeMap.ts:27

Creates a stream operator that maps each value from the source stream to an "inner" stream and merges all inner streams concurrently into a single output stream.

For each value from the source stream:

  1. The project function is called with the value and its index.
  2. The returned value is normalized into a stream using fromAny.
  3. The inner stream is consumed concurrently with all other active inner streams.
  4. Emitted values from all inner streams are interleaved into the output stream in the order they are produced, without waiting for other inner streams to complete.

This operator is useful for performing parallel asynchronous operations while preserving all emitted values in a merged output.

Type Parameters

T

T = any

The type of values in the source stream.

R

R = any

The type of values emitted by the inner and output streams.

Parameters

project

(value, index) => Stream<R> | CallbackReturnType<R> | R[]

A function that maps a source value and its index to either:

  • a <R>,
  • a <R> (value or promise),
  • or an array of R.

Returns

Operator<T, R>

An Operator instance that can be used in a stream's pipe method.

Examples

From mergeMap.spec.ts:4

typescript
const testStream = from([1, 2, 3]);
const project = (value: number) => from([value * 2, value * 4]);
const mergedStream = testStream.pipe(mergeMap(project));
let results: any[] = [];
mergedStream.subscribe({
  next: (value) => results.push(value),
  complete: () => {
    results.sort((a, b) => a - b);
    expect(results).toEqual([2, 4, 4, 6, 8, 12]);
    done();
  },
});

Released under the MIT License.