0
votes

I have a component X that needs an outcome of subscription to multiple observables and than send this outcome to component Y. These are the observables that must be somehow united to produce the result that I need:

  1. getChosenCityId (behaviourSubject) // once I have id, I can get city like so:
  2. getCityById(id) (result of a http call)

// Once I have the city, which is an object, I need its property - cityLocation

  1. getCitiesByLocation(cityLocation) (result of a http call) // cityLocation from the previous line
  2. getNearbyCities. (behaviorSubject) Returns a boolean. If it is true, I need

a)

  • citiesByLocation (4.)
  • chosenCityId (1.)

and if it is false, I need:

b)

  • city (2.)
  • chosenCityId(1.)

a) and b) are the outcomes that I need to send to the component Y (with next). How can I chain all these observables?

2
see this..actually, there are lot of questions regarding chaining observables, surely some question will help you. - Ramesh Reddy

2 Answers

2
votes

kind of hard to interpret this but something like...

this.getChosenCityId.pipe( // get id
  switchMap(id => this.getCityById(id)), // fetch the city
  withLatestFrom(this.getNearbyCities), // with the latest from get nearby
  switchMap(([city, getNearby]) => 
    getNearby // if get nearby, then get cities by location and map
      ? this.getCitiesByLocation(city.location).pipe(map(nearbyCities => ({city, nearbyCities})))
      : of({city}) // else just return the city
  )
).subscribe(result => console.log(result))

the set up would be a little different if you also want to automatically update if getNearbyCities changes:

combineLatest(this.getChosenCityId, this.getNearbyCities).pipe( // run when either emits
  switchMap(([id, getNearby]) => 
    this.getCityById(id).pipe(
      switchMap(city => 
        getNearby 
          ? this.getCitiesByLocation(city.location).pipe(map(nearbyCities => ({city, nearbyCities})))
          : of({city})
      )
    )
  )
).subscribe(result => console.log(result))
3
votes

Use a higher map operator like switchmap:

nearbyCities$ = getChosenCityId.pipe(
  switchMap(id => getCityById(id)),
  switchMap(city => getCitiesByLocation(city.location)),
);