1

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

3 Answers 3

1

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
      );
    }),
  );
}
Sign up to request clarification or add additional context in comments.

1 Comment

I choose the first suggestion, cause it was first :-) but thx anyway
0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.