lbrahim
lbrahim

Reputation: 3810

Flattening nested Observables.subscribe

I am new to Observables with rx.js and I wanted to know how I can flatten the following callback hell:

function getdata1 (argument) {
    return this.http.get(url)
        .map((res: Response) => res.json());
}

function getdata2 (argument) {
    return this.http.get(url)
        .map((res: Response) => res.json());
}

getdata1.subscribe((data1: any) => {
    console.log("got data one. get data 2 now");
    getdata2.subscribe((data2: any) => {
        console.log("got data one and two here");
    });
});

I know if this was Promises, then() could have been used to flatten it. But I do not know the equivalent of then() in Observables.

Upvotes: 4

Views: 3132

Answers (1)

Thierry Templier
Thierry Templier

Reputation: 202138

You could use the flatMap operator with Observable.forkJoin:

getdata1().flatMap(data1 => {
  return Observable.forkJoin([
    Observable.of(data1);
    getdata2()
  ]);
}).subscribe(result => {
  var data1 = result[0];
  var data2 = result[1];
  (...)
});

Upvotes: 4

Related Questions