Demo: switchAll
The switchAll operator switches to subscribe the latest observable from the source stream and cancels (i.e. un-subscribes) the previous observable, if it is still in progress.
It is useful for the use cases where the latest request is important to us and the older ones are considered as obsolate, hence, need to be discarded.
const source = timer(0,2000).pipe(take(4));
//Map each source item to this counting task
const countTill3Task = timer(0,1500).pipe(take(4));
//switchAll will immediately switch to run the latest task as it arrives.
const switchAllOutput = source
.pipe( map(v => countTill_3_Task))
.pipe( switchAll())
.subscribe(v => console.log(v));
The switch All operator enables us to switch to subscribe the latest observable from the source stream. And cancel (or un-subscribe) the previous observable, if it is still in progress.
Let's verify how it works using our demo.
- We are mapping each of our input from the source to an observable which is a simple count till 3 task.
Since we are passing these tasks to the switch All operator as a stream:
- We can observe that the operator is always switching to subscribe the latest counting task as soon as it arrives.
- Moreover, it also cancels the previous in-progress counting task.
For instance:
- When the counting task for 1 arrived, counting for 0 has progressed only till 1. But, the operator stopped the counting for 0 and started it for the new request.
- Same thing happened for 1 when the task for 2 arrived and again for 2 when the task for 3 arrived.
- The task for 3 ran till completion because no new task arrived in between.
The switchAll accepts a stream of observables as its input. The RxJs provides another a similar but, a more powerful method in - switchMap which combines the features of :
- Map : (map raw input data) => (observables representing our desired tasks) and
- Execute : switchAll operator that switch to execute the latest observable,
- cancelling the previous observable, if it is still in-progress.
For example, here are two equivalent code using the two:
const input = timer(0,2000).pipe(take(4));
const countTill_3_Task = timer(0,1500).pipe(take(4));
//1. Code with switchAll
const switchAllOutput = input
.pipe( map(v => countTill_3_Task))
.pipe( switchAll());
//2. Equivalent code using switchMap
const switchMapOutput = input
.pipe( switchMap(v => countTill_3_Task));
In Short :
switchMap => map + switchAll, switch to the latest the mapped observable.
We will look at more usage of these switchMap/switchAll under switchMap.