How can I get values from two observables sequentially?

Anthony Cloquette :

I'm a newbie with RxJs.

My purpose is : (1) make a first call backend and get value, then (2) based on the returned value, make an other call backend and return both values as an array.

When I subscribe, I would like get both values : building and buildingUnit.

This is the way of I trying to achieve this purpose :

this._buildingsService.loadBuilding(1).pipe(
  mergeMap((b: Building) => {
    if (b) {
      return this._buildingUnitsService.loadBuildingUnit(b);
    }
  })
).subscribe((bu: BuildingUnit) => {

});

The kind of result that I would like to get back :

this._buildingsService.loadBuilding(1).pipe(
  mergeMap((b: Building) => {
    if (b) {
      return this._buildingUnitsService.loadBuildingUnit(b);
    }
  })
).subscribe((b: Building, bu: BuildingUnit) => {

});

Thank you

martin :

You can just map the second value into an array.

this._buildingsService.loadBuilding(1).pipe(
  mergeMap((b: Building) => {
    if (b) {
      return this._buildingUnitsService.loadBuildingUnit(b).pipe(
        map(c => [b, c]),
      );
    }
    return of([b]); // or `[b, undefined]` to be more obvious
  })
  .subscribe(([b, c]) => {
    // ...
  })

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29962&siteId=1