but I wonder whether I should avoid nesting two flows of reactive operators, and whether there is a better way to write that
I'd say it depends on what you want to achieve, at least in this case.
of([1,2,3]).pipe(mergeAll(), switchMap(value => http.get(...)))
differs from
of([1,2,3]).pipe(switchMap(ids => from(ids).pipe(mergeMap(...))))
In the first scenario, each inner observable will be discarded by the next value(except for the last value), so only 3 will resolve.
In the second scenario, it will process all of them, because you explode the array in the inner observable(which is managed by swtichMap
, so the only way its inner observable will be discarded is if a new outer value(e.g another array of ids) is emitted by the source).
A case where nesting is not necessary is:
of([1,2,3])
.pipe(
// whenever you want to explode an array,
// it does not matter which higher order operator you use
// since the operation is **synchronous**
// so, `mergeAll`, `concatAll`, `switchAll` should work the same
mergeAll(),
mergeAll(id => this.apiService.useId(id))
)
// same as
of([1,2,3])
.pipe(
mergeMap(ids => from(ids).pipe(mergeMap(id => this.apiService.useId(id))))
)
As you can see, in this case, switchMap
has been replaced with mergeMap
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…