Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute dynamically created array of observables in series

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

like image 569
user2869612 Avatar asked Mar 31 '17 05:03

user2869612


1 Answers

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
like image 166
martin Avatar answered Oct 03 '22 09:10

martin