BACK
ReferenceswitchMap
Reference · 21

switchMap

switchMap

rxjs.dev

Switches to a new inner stream, cancelling the previous one.

Signature

switchMap(project: (value: T, index: number) => ObservableInput): OperatorFunction

Marble diagram

outer:    --a---b---c---|
inner(a): xxxxx (cancelled)
inner(b): xxxxx (cancelled)
result:   --------------c-c-c-|

What it does

For each outer value it starts project(value) — an inner Observable — subscribes to it, and unsubscribes from the previous inner one. The stream's output is only the current inner's emissions.

When to use

Typeahead search (the latest request matters, earlier ones are cancelled), navigating to a new page (cancel the old request), reacting to a parameter change.

Gotcha

Risky for critical submit operations — the inner request can be cancelled midway. For submits, use exhaustMap or concatMap.

See also

mergeMap, concatMap, exhaustMap

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...