Search code examples
angularrxjsangular6rxjs6

Sequential cascade Observables according result from previous response and remap to new data object


I have difficulties using the power of Observables i.e. RxJs 6 to correctly pipe, tap, map, mergemap or whatever my HttpClient requests. The version hell with all the different functions makes it not very easy...

So what I need is to first make a REST call, then depending on the result probably do a second REST call and map the potentially two received data objects in one new data object. The function should return an Observable.

So currently, I solved it with a subject that I am be able to do manually / sequentially what I need. The function returns a Subject, not an Observable in this case. But since the caller just subscribes to this function, it works. To mention is that the two service functions below (userService.loadUserDetails() and adminService.getAdminData()) just returns observables they get from HttpClient.

So can anybody help me translate this example code below into typically RxJs 6 code?

myFunction(): Observable<any> {
   const s = new Subject();
    let obj: any = {};

    this.userService.loadUserDetails().subscribe((userDetails) => {
        obj.user = userDetails;
        if (userDetails.authorities.includes('ADMIN')) {
            this.adminService.getAdminData().subscribe((adminData) => {
                obj.adminData = adminData;
                s.next(obj);
                s.complete();
            });
        } else {
            s.next(obj);
            s.complete();
        }
    });

    return s;
}

Solution

  • Use mergeMap to chain and return conditionally

    Update: changed mergeMap to switchMap Incase inner observable is a continuous stream and when source observable emit it will also cancel the inner observable .

        this.userService.loadUserDetails().pipe(
        switchMap(user=>
          user.authorities.includes('ADMIN')) ?
          this.adminService.getAdminData().map(adminData=>({adminData,user})):
          Observable.of({user}))
          )
        .subscribe();