RxJs: Executing 3 observables one after another and using results from first in second, and first and second in third requests

孤街浪徒 提交于 2020-07-20 11:30:58

问题


I need to be able to execute 3 observables one after another so that I can use result value from 1st one in second and also 1st and 2nd result in the third one.

Something like this (it doesn't work as the serviceId is not visible in the third request):

private setupStuff(): void {
        this.initRouteParams().pipe(
            switchMap(serviceId => this.getFileInfo(serviceId)),
            switchMap(fileName => this.getExistingFile(serviceId, fileName)
                .subscribe(response => {
                    console.log(response);
                }))
            );
    }

回答1:


You can explicitly return the value of the serviceN to the serviceN+1. Here's the idea :

private setupStuff() {
  this.initRouteParams()
    .pipe(
      switchMap(serviceId => {
        return zip(of(serviceId), this.getFileInfo(serviceId))
      }),
      switchMap(([serviceId, filename]) => {
        return zip(of(serviceId), of(filename), this.getExistingFile(serviceId, filename))
      })
    )
    .subscribe(([serviceId, filename, response]) => {
      console.log(serviceId, filename, response);
    })
}

Edit:

You can fix types errors by explicitly declare types of each input. You probably want to assign the appropriate type for response.




回答2:


managed to solve it like this:

private checkFilePresence(): void {
        const first$: Observable<string> = this.initRouteParams();
        const second$: Observable<string> = first$.pipe(
            switchMap(config => {
                return this.getFileInfo(config);
            })
        );
        const third$: Observable<CkitExistingFileResponse> = combineLatest(first$, second$).pipe(
            switchMap(([config, second]) => {
                return this.getExistingFile(config, second);
            })
        );
        combineLatest(first$, third$)
            .subscribe(() => {
            });
    }



回答3:


You can subsribe to observables in sequence as below:

private setupStuff(): void {
        this.initRouteParams().subscribe( serviceId => {
            this.getFileInfo(serviceId).subscribe(fileName => {
               this.getExistingFile(serviceId, fileName).subscribe( response => {
                   console.log(response);
                });
            });
        });
}


来源:https://stackoverflow.com/questions/51601510/rxjs-executing-3-observables-one-after-another-and-using-results-from-first-in

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