Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 406
lbrahim Avatar asked Sep 01 '25 00:09

lbrahim


1 Answers

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];
  (...)
});
like image 193
Thierry Templier Avatar answered Sep 02 '25 13:09

Thierry Templier