Skip to content

Function: concatMap()

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

Defined in: operators/concatMap.ts:24

Creates a stream operator that maps each value from the source stream to a new inner stream (or value/array/promise) and flattens all inner streams sequentially.

For each value from the source:

  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 fully before processing the next outer value.

This ensures that all emitted values maintain their original sequential order.

Type Parameters

T

T = any

The type of values in the source stream.

R

R = T

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

Parameters

project

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

A function that takes a value from the source stream and its index, and returns 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 concatMap.spec.ts:13

typescript
let project: (value: any) => Stream = (value: any) => of('innerValue' + value);

const values = ['1', '2'];
const mockStream$ = from(values).pipe(
  concatMap((value: any) =>
    value === '2' ? errorInnerStream() : project(value)
  )
);
const emittedValues: any[] = [];
const errors: any[] = [];
mockStream$.subscribe({
  next: (value: any) => emittedValues.push(value),
  error: (error: any) => errors.push(error),
  complete: () => {
    expect(emittedValues).toEqual(['innerValue1']);
    expect(errors[0].message).toEqual('Inner Stream Error'); // Only second emission should throw
    done();
  },
});

Released under the MIT License.