Skip to content

@epikodelabs/streamix


@epikodelabs/streamix / switchMap

Function: switchMap()

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

Defined in: projects/libraries/streamix/src/lib/operators/switchMap.ts:33

Transforms each value from the source stream into a new inner stream, promise, or array, and emits values only from the most recently created inner stream.

When a new value is emitted from the source, the previous inner stream (if any) is cancelled and unsubscribed, and a new inner stream is created using the project function. Only values from the latest inner stream are emitted to the output. If the projected value is a <R> or array, it is normalized to a stream.

If the source completes and there is no active inner stream, the output completes. If an error occurs in the source, the projection function, or the inner stream, the output emits an error and completes.

Type Parameters

T

T = any

The type of values emitted by the source stream.

R

R = any

The type of values emitted by the projected inner streams.

Parameters

project

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

A function that receives each value and index from the source stream and returns a stream, a <R>, or array of values to be emitted.

Returns

Operator<T, R>

An operator function that can be applied to a stream, emitting values from the most recent inner stream created by the projection function.

Example

ts
// For each number, start a new timer stream and emit its ticks, cancelling the previous timer.
source.pipe(switchMap(n => timerStream(n)))

Released under the MIT License.