Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sequential subscription to an array of observables

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);
like image 670
R_BD Avatar asked Sep 24 '17 09:09

R_BD


People also ask

Is Forkjoin sequential?

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.

Can you subscribe to observable multiple times?

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.

Can you subscribe to an observable?

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.

What does subscribing to an observable mean?

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.


1 Answers

Alternate of forkJoin means you need to subscribe to the array of observables sequencially. mergeand 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 mergeand 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);
like image 60
Fiyaz Hasan Avatar answered Oct 19 '22 19:10

Fiyaz Hasan