Execute dynamically created array of observables in series

北城余情 提交于 2019-12-08 02:49:46

问题


I am working on a project (Angular2) where I am creating Observables dynamically and putting them in an array

var ObservableArray : Observable<any>[] = [];
//filling up Observable array dynamically
for (var i = 0; i < this.mainPerson.children.length; i++) {       
ObservableArray.push(Observable.fromPromise(this.determineFate(this.mainPerson.children[i])));
  }
}


var finalObservable: Observable<any> = Observable.concat(ObservableArray);

finalObservable
  .subscribe( data => {
    //here  I expected to execute determineFate() for all observables inside array  
    console.log("determine fate resolved data returned [" + data + "]");
  }, error => {
    console.error("error on Age Year for Characters")
  },() => {  
    //Here I expect this gets executed only when all Observables inside my array finishes 
    console.log("determine fate resolved data returned COMPLETED");
    //DB call
  });

  determineFate(..): Promise<boolean> {
       ...
       return either true / false if success or error;

 }

I want to execute all observables in a series (forkJoin seems to run in parallel - so used concat). Once all observables are executed, want to execute some DB related code. But it seems my code inside 'Completed' block does not wait for all Observables to finish. How can I achieve this?

Thanks in advance


回答1:


Using Observable.concat(ObservableArray) will just flatten the array and emit each Observable from ObservableArray one by one. Btw, using the static version of concat makes sense only with two or more parameters (see http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#static-method-concat).

Instead you can iterate the array of Observables and wait until they complete one by one with the concatAll() operator.

This example simulates your use-case:

var observableArray = [];
// filling up Observable array dynamically
for (var i = 0; i < 10; i++) {
  observableArray.push(Observable.of('Value ' + i));
}

Observable.from(observableArray)
  .concatAll()
  .subscribe(console.log, null, () => console.log('completed'));

The Observable.from() emits each Observable separately and concatAll() subscribes to each one of them in the order they were emitted.

This demo prints to console the following output:

Value 0
Value 1
Value 2
Value 3
Value 4
Value 5
Value 6
Value 7
Value 8
Value 9
completed


来源:https://stackoverflow.com/questions/43133405/execute-dynamically-created-array-of-observables-in-series

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