Reputation: 7864
I have 2 observables and my code is like this Stackblitz link
const obs1$ = of(1); // mock http call
const obs2$ = of(2);
obs1$.subscribe( (value1) => {
this.first = value1; // populating values from subscribe
})
obs2$.subscribe( (value2) => {
this.second = value2; // populating values from subscribe
})
forkJoin([obs1$,obs2$]).subscribe(() => {
if(this.first === 0 || this.second === 0) // checking if the values are not empty
console.log('empty')
});
How can I consolidate these 3 methods using RxJs, right now there are double http calls once from subscribe another from forkjoin.
I want to populate when both observables(together) have finished and get results also to populate first
and second
and check their values too
Upvotes: 0
Views: 640
Reputation: 2342
You can do that in forkJoin itself i.e -
const obs1$ = of(1).pipe(take(1)); // mock http call
const obs2$ = of(2).pipe(take(1));
forkJoin([obs1$,obs2$]).subscribe(([obs1Result, obs2Result]) => {
this.first = obs1Result;
this.second = obs2Result;
});
Also you may want to use combineLatest
instead of forkJoin
because it waits for both the observable to complete, while combineLatest
emits a value, each time source observable emits a value after all observables have emitted at least one value.
Upvotes: 2
Reputation: 1736
You can directly call forkJoin and access to the resultat :
forkJoin([obs1$, obs2$]).subscribe((result) => {
this.first = results[0];
this.second = results[1]
if (this.first === 0 || this.second === 0) // checking if the values are not empty
console.log('empty')
});
Upvotes: 3