避免嵌套订阅取决于可观察量的性质以及它们相互依赖的方式:
相互依赖的可观察量
当可观察到的(this.grants.get()
) 取决于来自另一个可观察的通知 (this.user
),您可以使用任何 RxJS 高阶映射运算符switchMap
, mergeMap
, concatMap
and exhaustMap
。每个人都有自己的目的。你可以发现它们之间的差异here https://blog.angular-university.io/rxjs-higher-order-mapping/.
它们之间的简短差异
-
switchMap
- 如果外部可观察值发出,则取消内部可观察值
-
mergeMap
- 为每个外部通知触发内部可观察(展平外部通知)
-
concatMap
- 本质上mergeMap
随时发出单个并发请求(展平外部通知但按顺序发出它们)
-
exhaustMap
- 如果内部可观察尚未完成,则忽略外部通知
插图使用switchMap
操作员
this.user.pipe(
switchMap(e => this.grants.get(e))
).subscribe((x) => {
console.log(x)
});
独立可观测量
如果可观察量彼此独立,您可以使用 RxJS 函数,例如forkJoin
, combineLatest
or zip
并行触发可观察量。
它们之间的简短差异
-
forkJoin
α - emit only when all the observables complete
-
combineLatest
α,β - emit when any of the observables emit (observables w/o emissions will emit old value)
-
zip
α,β - emit when all of the observables emit
插图使用forkJoin https://rxjs-dev.firebaseapp.com/api/index/function/forkJoin
forkJoin(this.obs1, this.obs2, ...).subscribe(
res => console.log(res)
);
α- 从每个可观察对象发出一系列通知(例如(this.obs1, this.obs2, ...)
会发出['res from obs1', 'res from obs2', ...]
).
β- 所有可观察到的should至少发射一次以便操作员发射