Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

212
Views
Avoiding nested subscribes with combine latest when one observable depends on the result of another

I have three observables I would like to combine into a single stream. However the third observable requires a property from the first observable -- is it possible to combine all three to avoid nested subscribes (for the sake of clarity)?

Observable.combineLatest(this.fooService.model, this.barService.model)
  .subscribe(result => {
    //do work

    this.bazService.anotherObservable(result[0].someProperty)
      .subscribe(anotherResult => {
        //do more work
      });
  });
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use switchMap and map to do what you want:

Observable
  .combineLatest(this.fooService.model, this.barService.model)
  .switchMap(([foo, bar]) => {
    return bazService
      .anotherObservable(foo.someProperty)
      .map((baz) => [foo, bar, baz]);
  })
  .subscribe(([foo, bar, baz]) => console.log(foo, bar, baz));

Whenever the combined foo and bar observables emit a value, the baz service will be called and its result will be futher combined.

Note that switchMap will abandon pending baz calls if the foo or bar observables re-emit. If you don't want that behaviour and always want the baz result to be emitted, use concatMap instead of switchMap.

Another option is to use mergeMap instead of concatMap - the latter will guarantee that the order of the baz calls will be preserved, the former won't.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!