Here, I've used forkJoin
from rxjs to subscribe to an array of observables parallelly. But I want to subscribe to them one by one, What will be the best solution?
Below is my code :
var observables = [];
Observable.forkJoin(observables)
.subscribe(() => {
this.msgs = [];
this.msgs.push({
severity: 'success',
summary: 'Saved Successfully'
});
this.onSaveComplete();
}, (error: any) => this.errorMessage = <any>error);
}, (error: any) => this.errorMessage = <any>error);
In parallel computing, the fork–join model is a way of setting up and executing parallel programs, such that execution branches off in parallel at designated points in the program, to "join" (merge) at a subsequent point and resume sequential execution.
It turns out that as the Observable is just a definition, let's remember that in a sense its something close to a function declaration, if we subscribe to it multiple times this means that each time a new HTTP request will be issued, one for each subscription.
SubscribinglinkAn Observable instance begins publishing values only when someone subscribes to it. You subscribe by calling the subscribe() method of the instance, passing an observer object to receive the notifications.
Subscribing to an Observable is like calling a function, providing callbacks where the data will be delivered to. This is drastically different to event handler APIs like addEventListener / removeEventListener . With observable. subscribe , the given Observer is not registered as a listener in the Observable.
Alternate of forkJoin means you need to subscribe to the array of observables sequencially. merge
and concat
are the ways to go in this case. In your case, modify your code and use a spread operator at the very beginning of your array of observables when using merge
and concat
.
var observables = [];
Observable.concat(...observables)
.subscribe(() => {
this.msgs = [];
this.msgs.push({
severity: 'success',
summary: 'Saved Successfully'
});
this.onSaveComplete();
}, (error: any) => this.errorMessage = <any>error);
}, (error: any) => this.errorMessage = <any>error);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With