Knack
Knack

Reputation: 1134

RxJs: How to invoke method when work in subscriptions of two observables is done

I'm loading data from different API endpoints and then do some synchronous work on each data set:

// Invoked by user interaction
loadData() {
    this.service1.getData().subscribe(
      data => {
        this.doSynchronousWork(data);
        this.data1 = data;
      }
    );

    this.service2.getData().subscribe(
      data => {
        this.doSynchronousWork(data);
        this.data2 = data;
      }
    );
}

// To be invoked when this.data1 and this.data2 is available
doSynchronousWorkWhenAllDataIsLoadedAndProcessed()

Now I need to invoke another synchronous method when both subscribtions have done their work. How can I do that?

Upvotes: 0

Views: 42

Answers (1)

Theophilus Omoregbee
Theophilus Omoregbee

Reputation: 2503

To achieve this, you use forkJoin, where you add up all your observables as an array and they run asynchronuously returning the data as an array like so

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

console.log("Owk ooo let's play small with observables ");

// this is just to form an asynchronous process
asyncSimulator(data: number): Observable < any > {
  return Observable.create(observer => {
    setTimeout(() => {
      observer.next("data to send can be object or anything" + data);
      console.log("am done");
      observer.complete(); //to show we are done with our processing 
    }, 2000);
  })
}

/** 
call the all asynchronous process here, like so with Fork Join
*/
Observable.forkJoin([
    this.asyncSimulator(1),
    this.asyncSimulator(2),
    this.asyncSimulator(3),
  ])
  .subscribe(results => {
    let async1 = result[0];
    let async2 = result[1];
    let async3 = result[1];
    console.log("results is an array", results);
  });

Hope this helps.

Upvotes: 3

Related Questions