lordscales91
lordscales91

Reputation: 433

Angular 2 synchronization issue - call a function after completing 2 async calls

I have an scenario where I need to call a function C after the functions A and B, which are executed asynchronously. Functions A and B retrieve data from the server which I need later to call function C, but each of them are independent.

I could just chain them, call A then call B after the data is retrieved and finally call C after retrieving the data of B. But since A and B don't rely on each other it makes more sense to run them in parallel and then after both complete run C.

Here some sample code:

ngOninit() {
    this.mySrv.getSomeStuff() // Returns an observable
        .subscribe(data => this.stuff = data);
    this.mySrv.getOtherStuff().subscribe(data => this.other = data);
    // I need both data to execute the next function
    this.mySrv.doSomething(this.stuff, this.other)
            .subscribe(data => {/* do something */});
}

Upvotes: 1

Views: 971

Answers (1)

AVJT82
AVJT82

Reputation: 73357

You could use Observable.forkJoin for the first two requests, which runs them in parallell. Then using flatMap (mergeMap) you can execute request based on the previous results and then finally subscribe. So something like this:

import {Observable} from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/mergeMap';

// ...

ngOnInit() {
  Observable.forkJoin(this.mySrv.getSomeStuff(), this.mySrv.getOtherStuff())
    .flatMap(data => {
      console.log(data[0]) // result of 'getSomeStuff()'
      console.log(data[1]) // result of 'getOtherStuff()'
      return this.mySrv.doSomething(data[0], data[1])
    })
    .subscribe(data => {
      console.log(data) // result of 'doSomething()'
    })
}

Upvotes: 2

Related Questions