Wait until two Observables are complete

我的未来我决定 提交于 2020-05-13 18:14:06

问题


I want to call a method after two Observables have returned values. I did some searching and it seems like forkJoin is what I want, but I can't get it to work. I know both of these Observables are returning values, as I am using the data for each individually elsewhere in the component, so clearly I'm doing something else wrong.

Here is what I tried. I'm using 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),
);

Nothing is logging to the console and I am not getting any errors. Again, the Observables I am passing in are definitely returning values.

Am I doing something wrong, or am I taking the wrong approach entirely by using forkJoin?


回答1:


forkJoin emits when all the observables complete, not when they emit.

You can use combineLatest instead.

Be careful to not import the instance operator from 'rxjs/operators'. It's a common mistake caused by some IDEs auto-import feature. In this case, we need the static version, imported from '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),
);


来源:https://stackoverflow.com/questions/55677695/wait-until-two-observables-are-complete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!