Search code examples
angularrxjs-observables

how to combine multiple observables on first observable complete and return as new observable in method


I am a beginner to use RxJs operators and I am having a requirement of a method, which calls 5 observables from service and it should fetch data from service only after first observable completes, then combine all the observables and transform to a new observable and return a new observable with in a function. The below code illustrates the scenario.

GetAllDetails(): Observable<AllDetails> {

const user = this.service.getUser() // Observable<User>
const firstDetails = this.service.getFirstDetail() // returns Observable<FirstDetail>
const secondDetails = this.service.getSecondDetail() // returns Observable<SecondDetail>
const thirdDetails = this.service.getThirdDetail() // returns Observable<ThirdDetail>
const fourthDetails = this.service.getFourthDetail() // returns Observable<FourthDetail>

// need to return a value that something compatible with Observable<AllDetails>
// so the logic should check if user info available then do combining all observable values and 
// return as new observable 

return of(new AllDetails(first, second, third, fourth) 
}

I tried using CombineLatest and switchMap, but I cannot achieve this after my first observable complete. Appreciate if someone could help me out on this.


Solution

  • You could try this:

    return user.pipe(
      last(), // Get the lastest value when the `user$` completes
      switchMap(
        user => conditionOnUser 
          ? forkJoin({ first: firstDetails, second: secondDetails /* ... */ })
          : of(null)
      ),
      map(
        detailsOrNull => !detailsOrNull
          ? false // No user info available
          : new AllDetails(detailsOrNull.first, detailsOrNull.second /* ... */)
      )
    )