Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
                }))
            );
    }
like image 820
Deniss M. Avatar asked Jul 30 '18 20:07

Deniss M.


1 Answers

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.

like image 127
madjaoue Avatar answered Oct 31 '22 14:10

madjaoue