Reputation: 344
I have 2 Observables number$ and text$. I want to subscribe to both simultaneously and get their values in an inner subscription.
My code now looks like this:
number$.subscribe((nr: number) => {
text$.subscribe((txt: string) => {
this.foo(nr, txt);
});
});
Is there any way to combine these two so i only need one subscription? I know about forkJoin (which probably would work perfectly fine here), but it's deprecated and we don't want to use deprecated functions.
Thanks in advance!
Upvotes: 1
Views: 8464
Reputation: 2987
I think you are looking for combineLatest or forkJoin, the different is combineLatest emit on every data fired on both Observable, and forkJoin emit when both Observable completed. In most case, you should use combineLatest
.
For example, when using combineLatest
, source number$
fired an value but source text$
didn't fire, then the pipeline wait for text$
to fire an value and then emit both of them to the subsriber, then keep emit the latest value from both source whenever they fire a new value. And remember to unsubscribe them on destroy.
combineLatest(number$,text$).subscribe(([numberValue,textValue]) => {
// Do your logic
})
Upvotes: 1
Reputation: 2925
If you want to fire the events in parallel you should use fork join.
If you want to call the events one after the other you can use either merge map or switch map.
Upvotes: 1