preface
SwitchAll, concatAll, and mergeAll are operators that convert higher-order observable values to first-order observable values, which can be understood as flattening, like converting a two-dimensional array into a one-dimensional array
What are higher-order observables? Observables of observables are called high-order observables (Observable<Observable<T>>)
case
import { fromEvent, interval } from 'rxjs'
import { map, take, switchAll, delay, concatAll, mergeAll } from 'rxjs/operators';
const example = fromEvent(document.'click')
// Click twice
example.pipe( map(e= > interval(1000).pipe(delay(3000), take(3))), concatAll(), map(a= > 'concat' + a) ) .subscribe((value) = > { console.log(value); }); / * concat0 concat1 concat2 concat0 concat1 concat2 * / example.pipe( map(e= > interval(1000).pipe(delay(3000), take(3))), mergeAll(), map(a= > 'merge' + a) ) .subscribe((value) = > { console.log(value); }); / * merge0 merge0 merge1 merge1 merge2 merge2 * / example.pipe( map(e= > interval(1000).pipe(delay(3000), take(3))), switchAll(), map(a= > 'switch' + a) ) .subscribe((value) = > { console.log(value); }); / * switch0 switch1 switch2 * / Copy the code
The difference
concatAll
The next Observable is processed after the previous Observable is processed. Observables are executed one by one. For example, take concat0 after 4 seconds, concat1 after 5 seconds, concat2 after 6 seconds; Concat0 after 10 seconds, concat1 after 11 seconds, concat2 after 12 seconds
mergeAll
It can process all Observables in parallel at the same time. As shown above, the corresponding data will be output according to the output time of each Observable after two clicks, just like several interface requests. No matter where you send it, the one who first requests the data will output the corresponding data first. This is done until the last request succeeds and the final data is printed
switchAll
The output of the new Observable directly processes the new Observable. No matter whether the previous Observable is complete or not, the old Observable will be unsubscribe as long as a new Observable is sent out. Always only deal with the latest Observable. If the above two clicks are connected, the first Observable will be output after 4 seconds, and the second one will have a new Observable, so the first subscription will be canceled and the data of the second one will be output after 4 seconds
Online code sample
If there are any mistakes in this article, please correct them in the comments section. If this article has helped you, please like it and follow it
This article is formatted using MDNICE