switchMap
signature: switchMap(project: function: Observable, resultSelector: function(outerValue, innerValue, outerIndex, innerIndex): any): Observable
switchMap(project: function: Observable, resultSelector: function(outerValue, innerValue, outerIndex, innerIndex): any): Observable
Map to observable, complete previous inner observable, emit values.
:bulb: If you would like more than one inner subscription to be maintained, try mergeMap
!
:bulb: This operator is generally considered a safer default to mergeMap
!
:bulb: This operator can cancel in-flight network requests!
Why use switchMap
?
switchMap
?The main difference between switchMap
and other flattening operators is the cancelling effect. On each emission the previous inner observable (the result of the function you supplied) is cancelled and the new observable is subscribed. You can remember this by the phrase switch to a new observable.
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.
Be careful though, you probably want to avoid switchMap
in scenarios where every request needs to complete, think writes to a database. switchMap
could cancel a request if the source emits quickly enough. In these scenarios mergeMap is the correct option.
Examples
Example 1: Restart interval on every click
( StackBlitz )
Example 2: Countdown timer with pause and resume
( StackBlitz )
Example 3: Using a resultSelector function
( StackBlitz )
Related Recipes
Additional Resources
:newspaper: - Official docs
Avoiding switchMap-Related Bugs -
Nicholas Jamieson
Starting a stream with switchMap
:video_camera: :dollar: - John Linquist
Use RxJS switchMap to map and flatten higher order observables
:video_camera: :dollar: - André Staltz
Use switchMap as a safe default to flatten observables in RxJS
:video_camera: :dollar: - André Staltz
Build your own switchMap operator
:video_camera: - Kwinten Pisman
:file_folder: Source Code: https://github.com/ReactiveX/rxjs/blob/master/src/internal/operators/switchMap.ts
Last updated