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

六月ゝ 毕业季﹏ 提交于 2020-05-15 05:09:50

问题


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;
}

回答1:


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();



回答2:


You can create your own observer. import { Observable } from 'rxjs/Observable';

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


来源:https://stackoverflow.com/questions/50981109/sequential-cascade-observables-according-result-from-previous-response-and-remap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!