Skip to content

Function: switchMap()

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

Defined in: operators/switchMap.ts:27

Creates a stream operator that maps each value from the source stream to a new inner stream and "switches" to emitting values from the most recent inner stream, canceling the previous one.

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 operator subscribes to the new inner stream and immediately cancels any previous active inner stream.
  4. Only values from the latest inner stream are emitted.

This operator is useful for scenarios such as:

  • Type-ahead search where only the latest query results are relevant.
  • Handling user events where new events invalidate previous operations.

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 suitable for use in a stream's pipe method.

Examples

From switchMap.spec.ts:4

typescript
const testStream = from([1, 2, 3]).pipe(delay(100));
const project = (value: number) => from([value * 10, value * 100]);
const switchedStream = testStream.pipe(switchMap(project));
let results: any[] = [];
switchedStream.subscribe({
  next: (value) => results.push(value),
  complete: () => {
    expect(results).toEqual([10, 100, 20, 200, 30, 300]); // Should switch to new inner streams and emit all values
    done();
  },
});

Released under the MIT License.