Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combining multiple Observables

I have these 2 observables:

this.areasService.getSelectAreas({})
   .subscribe((result) => this.areasSelect = result.json().data.areas);
this.stationsService.getSelectStations({})
   .subscribe((result) => this.stationsSelect = result.json().data.stations);

that fills these 2 variables (async) this.areasSelect & this.stationsSelect.

I also have a 3rd observable that I need to have these values to continue:

this.transportsService.getTransport().subscribe((res) => {
     console.log(this.areasSelect)
     console.log(this.stationsSelect)
})

How can I combine these 3 observables?

like image 680
Michalis Avatar asked Jun 18 '17 13:06

Michalis


Video Answer


2 Answers

All you need to do is to use forkJoin , it will call both of your first async calls and only returns data on both completion , so no need to worry

After that on subscribe you will get result in array of sequence you called the urls or apis.

const combined = Observable.forkJoin(
    this.areasService.getSelectAreas({}).map((res) => res.json().data.areas),
    this.stationsService.getSelectStations({}).map((res) => res.json().data.stations)
)

combined.subscribe(latestValues => {

    this.areasSelect = latestValues[0];
    this.stationsSelect = latestValues[1];

    this.transportsService.getTransport().subscribe((res) => {
        console.log(this.areasSelect)
        console.log(this.stationsSelect)
    })
});
like image 121
Vivek Doshi Avatar answered Oct 27 '22 07:10

Vivek Doshi


You could use forkJoin:

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

let areaSelect$ = this.areasService.getSelectAreas({})
.map(res => res.json().data.areas)
.do(val => this.areaSelect = val);

let stationSelect$ = this.stationsService.getSelectStations({})
.map(res => res.json().data.stations)
.do(val => this.stationSelect = val);

forkJoin(areaSelect$,stationSelect$)
.mergeMap(data=>{
   //data is an array with 2 positions which contain the results of the 2 requests. data[0] is the vale of this.areaSelect for example
   return this.transportsService.getTransport(data[0],data[1]);
}).subscrite(res => {
  // res is the response value of getTransport
})
like image 34
Jota.Toledo Avatar answered Oct 27 '22 07:10

Jota.Toledo