Kheber
Kheber

Reputation: 327

How to merge multiple Observable responses

I'm trying to merge multiple responses from Observables to one stream. I'm fetching companies and each company has multiple inspections (which are stored as IDs). For each inspection I have to fetch the respective data.

This is how my code currently looks like. Please check the commented out section for the current result.

// Get companies
getCompanies().pipe(
   switchMap(companies => companies.map(
     company => {
       return company['inspections'].map(inspection => {
         // Get inspections by each company
         return this.getInspectionById(inspection['id']);
       })
     }
   ))
).subscribe(result => {
   /* 
     console.log(result) returns the following (company1 has two inspections, company2 has three 
     inspections):

     (2) [Observable, Observable]
       0: Observable
       1: Observable

     (3) [Observable, Observable, Observable]
       0: Observable
       1: Observable
       2: Observable
   */
});

As you can see, my subscription currently returns the Observables only. I guess I'm just missing the part for merging the data streams, I've tried different operators like mergeMap, combineLatest, forkJoin etc. but didn't found the right one.

My desired output would be something like this (quite the same as above, but real data instead of observables):

company1:
   company_data: ...
   inspections: [a, b]

company2:
   company_data: ...
   inspections: [a, b, c]

Does anybody know which operator to use and how to do it? Thank you in advance!

Upvotes: 0

Views: 1431

Answers (2)

Owen Kelvin
Owen Kelvin

Reputation: 15083

You probably looking for forkJoin operator for this case, something like below

getCompanies().pipe(
  switchMap(companies => forkJoin(
     companies.map(company => forkJoin(
       company['inspections'].map(inspection =>
         this.getInspectionById(inspection['id'])
       )
     ).pipe(
         map(inspections => ({...company, inspections }))
       )
     )
   ))
)

forkJoin will combine the observable array and return a single Observable

Upvotes: 2

user13548229
user13548229

Reputation:

If I understand your question right I think you are confused in your approach. As far as I understood you have observables inside your observable. You subscribe your wrapper observable and get correctly the inner observables. Now you need the value of those. For that this might be helpful: Get current value from Observable without subscribing (just want value one time).

Upvotes: 0

Related Questions