简体   繁体   中英

forkJoin for multiple NgRx Store subscription

I have multiple store subscriptions in an array and I want to use forkJoin to get the result only when all observables return a result. Something like that:

this.subscriptionsArray = this.store.select('state')
forkJoin(this.subscriptionsArray).subscribe(sub => {
  // do something here with response
});

The problem is that the store doesn't emit anything.

I found a solution on a GitHub repo:

this.subscriptionsArray = this.store.select('state').pipe(first())

This work, but I need the last emitted result and the obvious solution doesn't work. The following code doesn't work:

this.subscriptionsArray = this.store.select('state').pipe(last())

In my opinion your observable is not fire and forget type, so you can not get the last emitted value, because:

Emit the last value emitted from source on completion, based on provided expression.

Reference: last filtering operator

You should try combineLatest :

When any observable emits a value, emit the latest value from each.

combineLatest(...this.subscriptionsArray).subscribe(value => console.log(value))

you can use withLatestFrom operator, so your code can be like:

const sub = this.store.select(selectStore1).pipe(
  first(),
  withLatestFrom(this.store.select(selectStore2).pipe(first())),
  concatMap(([selectStore1, selectStore2]) => {
    // do something
  })
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM