简体   繁体   中英

Combine the result of two depending observables (Rxjs)

i have two observables A and B. I first have to get A until i could take B.

If they are independently i could do something like forkJoin to get the result. But due to the fact i could take B only after i got A i am struggeling a little. I tried switchMap, but seems also not to work.

So what i want to achive is:

  • get observable A
  • get observable B
  • combine A and B into a result C

     public loadConfiguration(): Observable<ProductConfiguration> { return this.service.getA().pipe( switchMap(response => { return this.service.getB(response.id); } ), map(result => this.getData(result)) // here i want A and B thogether so result should contain A and B ); }

Currently i am a little lost. Regards Oliver

You can do it like this:

public loadConfiguration(): Observable<ProductConfiguration> {
  return this.service.getA().pipe(
     switchMap(response => {
      return this.service.getB(response.id).pipe(
        map(responseB => ({responseA: response, responseB})),
      );
     }),
     map(result => this.getData(result)) // result already have responseA & responseB
  );
}

Or this:

public loadConfiguration(): Observable<ProductConfiguration> {
  return this.service.getA().pipe(
    switchMap(response => {
      return this.service.getB(response.id).pipe(
        map(responseB => this.getData(...)), // you have access to response and responseB here
      );
    }),
  );
}

Try to use zip method to combine both results of both Observable:

public loadConfiguration(): Observable<ProductConfiguration> {
    return this.service.getA().pipe(
        switchMap(response => {
            return Observable.zip(
                this.service.getB(response.id),
                of(response)
            ); 
            return this.service.getB(response.id);
        })),
        .subscribe(([resA, resB]) => {
            console.log('resA', resA);
            console.log('resB', resB);

        }

According to ReactiveX:

zip combines the emissions of multiple Observables together via a specified function and emit single items for each combination based on the results of this function

Work example can be seen at stackbitz.com.

You can use the second argument of the switchMap (resultSelector) to combine the result:

public loadConfiguration(): Observable<ProductConfiguration> {
        return this.service.getA()
                   .pipe(
                       switchMap(response => this.service.getB(response.id), (a, b) => this.getData({a, b})),
                   );
    }

rxjs learn switchMap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM