【问题标题】:Wait until two Observables are complete等到两个 Observable 完成
【发布时间】:2019-04-14 16:45:29
【问题描述】:

我想在两个 Observables 返回值后调用一个方法。我做了一些搜索,似乎forkJoin 是我想要的,但我无法让它工作。我知道这两个 Observable 都在返回值,因为我在组件的其他地方单独使用每个数据,所以很明显我做错了。

这是我尝试过的。我正在使用 rxjs v6.4。

forkJoin(
  this.store.pipe(select(fromStore.getAppointmentsLoading)),
  this.clientStore.pipe(select(fromClientStore.getClientsLoading)),
).subscribe(
  ([res1, res2]) => {
    console.log('res1', res1);
    console.log('res2', res2);
  },
  err => console.error(err),
);

没有任何东西记录到控制台,我也没有收到任何错误。同样,我传入的 Observable 肯定是返回值。

我是在做错什么,还是我完全使用 forkJoin 采取了错误的方法?

【问题讨论】:

  • forkJoin 一直等到所有源完成,这种情况会发生吗?也许尝试combineLatestzip 看看它们是否在未完成的情况下发出。

标签: angular rxjs ngrx fork-join


【解决方案1】:

forkJoin 在所有可观察对象完成时(或其中一个抛出错误)发出,而不是在它们发出时发出。

您可以改用combineLatest

注意不要'rxjs/operators' 导入实例运算符。这是由某些 IDE 自动导入功能引起的常见错误。在这种情况下,我们需要从'rxjs' 导入的静态版本:

import {combineLatest} from 'rxjs';

combineLatest([
  this.store.pipe(select(fromStore.getAppointmentsLoading)),
  this.clientStore.pipe(select(fromClientStore.getClientsLoading)),
]).subscribe(
  ([res1, res2]) => {
    console.log('res1', res1);
    console.log('res2', res2);
  },
  err => console.error(err),
);

【讨论】:

  • 我怎样才能做同样的事情,同时在两个 observables 都完成时调用一个方法?
  • 老兄 combineLatest 的问题是它还结合了空值,我们通过它来初始化一个behaviorSubject observable。
  • skip(1) 添加到BehaviorSubject 以忽略第一个发射。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-18
  • 1970-01-01
  • 2018-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-06
相关资源
最近更新 更多