SwitchMap

Projects each source value to an Observable which is merged in the output Observable, emitting values only from the most recently projected Observable.

Returns

OperatorFunction<T, ObservedValueOf<O> | R>: An Observable that emits the result of applying the projection function (and the optional deprecated resultSelector) to each item emitted by the source Observable and taking only the values from the most recently projected inner Observable.

Returns an Observable that emits items based on applying a function that you supply to each item emitted by the source Observable, where that function returns an (so-called "inner") Observable. Each time it observes one of these inner Observables, the output Observable begins emitting the items emitted by that inner Observable. When a new inner Observable is emitted, switchMap stops emitting items from the earlier-emitted inner Observable and begins emitting items from the new one. It continues to behave like this for subsequent inner Observables.

import { of } from 'rxjs';
import { switchMap } from 'rxjs/operators';
 
const switched = of(1, 2, 3)
 .pipe(switchMap((x: number) => of(x, x ** 2, x ** 3)));
switched.subscribe(x => console.log(x));
// outputs
// 1
// 1
// 1
// 2
// 4
// 8
// ... and so on

Rerun an interval Observable on every click event

import { fromEvent, interval } from 'rxjs';
import { switchMap } from 'rxjs/operators';

const clicks = fromEvent(document, 'click');
const result = clicks.pipe(switchMap((ev) => interval(1000)));
result.subscribe(x => console.log(x));

This works perfectly for scenarios like typeaheads where you are no longer concerned with the response of the previous request when a new input arrives. This also is a safe option in situations where a long-lived inner observable could cause memory leaks, for instance, if you used mergeMap with an interval and forgot to properly dispose of inner subscriptions. Remember, switchMap maintains only one inner subscription at a time, this can be seen clearly in the first example.

Helping notes:Un observable es frío cuando el estado en la función de producción no se comparte entre sus suscriptores; y es caliente cuando sí es compartido. El concepto de frío/caliente también se conoce unicast/multicast.

Last updated