The switchAll
function in the rxjs
library allows you to flatten an Observable-of-Observables. It subscribes to each inner Observable as it arrives, but discards the previous inner Observable if a new one arrives before the previous completes.
Here's an example of how to use switchAll
:
index.tsx279 chars10 lines
In this example, we create an observable that emits the values 1000, 2000, and 3000 at 1s, 2s, and 3s respectively. We then use the map
operator to create a new inner Observable for each emit that delays for the value of the previous Observable. switchAll
is then used to subscribe to these inner Observables and only emit the latest observable values while canceling the previous subscriptions to the previous inner Observables. Finally, we subscribe to the switchAll
source and log the emitted values to the console.
This will output the following:
index.tsx54 chars4 lines
gistlibby LogSnag