Sequential subscription to an array of observables

心已入冬 提交于 2019-12-23 09:17:30

问题


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);

回答1:


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);



回答2:


Use the switchMap operator to make a series of dependant requests. Error will propagate and you can catch or otherwise handle them at the end of the chain.

return this.http.get('something/1')
  .switchMap(res1 => {
    // use res1 if you need it
    return this.http.get('something/2')
  })
  .switchMap(res2 => {
    // use res2 if you need it
    return this.http.get('something/3')
  })
  .subscribe(res3 => {
    // use the final response
    console.log(res3)
  })


来源:https://stackoverflow.com/questions/46388455/sequential-subscription-to-an-array-of-observables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!