I need to perform an action, after retrieving 2 objects from my store (ngrx), so, I need both calls to have responded before performing my action, like this :
const item1$: Observable<Item> = this._store$.select(
ItemStoreSelectors.selectItemById(this.id1)
);
const item2$: Observable<Item> = this._store$.select(
ItemStoreSelectors.selectItemById(this.id2)
);
let item1: Item;
item1$.pipe(take(1)).subscribe((item: Item) => {
item1 = item;
});
let item2: Item;
item2$.pipe(take(1)).subscribe((item: Item) => {
item2 = item;
});
// here, items might not have been initialized
doSomething(item1, item2);
I tried to look out for a solution in rxjs with switchMap, mergeMap, etc, but couldn't apply it to my needs. I think I found a solution doing async/await, but I'm not sure this is a good practice.
Thanks for your help.
Refactor into the following code :
import { forkJoin } from 'rxjs';
const item1$: Observable<Item> = this._store$.select(
ItemStoreSelectors.selectItemById(this.id1)
);
const item2$: Observable<Item> = this._store$.select(
ItemStoreSelectors.selectItemById(this.id2)
);
forkJoin([item1$.pipe(take(1)), item2$.pipe(take(1))])
.subscribe(([item1,item2])=>doSomething(item1,item2));