Last updated
Last updated
switchMap(project: function: Observable, resultSelector: function(outerValue, innerValue, outerIndex, innerIndex): any): Observable
💡 If you would like more than one inner subscription to be maintained, try !
💡 This operator is generally considered a safer default to !
💡 This operator can cancel in-flight network requests!
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 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 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 .
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 is the correct option.
Example 1: Restart interval on every click
( )
Example 2: Countdown timer with pause and resume
Example 3: Using a resultSelector
function
( )
( )
📰 - Official docs
- In Depth Dev Reference
- Nicholas Jamieson
🎥 💵 - John Linquist
🎥 💵 - André Staltz
🎥 💵 - André Staltz
🎥 - Kwinten Pisman
📁 Source Code: