Wait until two Observables are complete

2020-07-25 01:07发布

问题:

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),
);