0
votes

I want to pass values of an Observable to two distinct Observables.

For simplicity, suppose I have an Observable created from a dictionary that has two values: obs = rxjs.Observable.of({a: 1, b: 2}).
I first want to pass the first value a to another Observable which returns nothing: obs => rxjs.Observable.interval(obs.a*1000).
After this stream is completed, I next want to pass the second value b to other Observable which returns a single value: obs => rxjs.Observable.of(obs.b*2).
Finally I would like to get the last value: b*2=4.
(In my real app, all Observables are HttpRequest objects.)

I first thought of doing this by converting all Observables to Promises and use await. But I was wondering if I can do it within RxJS.
Is there any way to do this only by RxJS operators? I appreciate your help!

1

1 Answers

0
votes

You could try to use two switchMap combined with a map operator. Try the following

this.http.get('request1').pipe(   // <-- first request
  switchMap((res) =>              // <-- second request that doesn't return anything
    this.http.post('request2', res.a).pipe(   // <-- use only property `a` from first request
      map(_ => res)               // <-- map back to result from first request
    )
  ),
  switchMap(({ b }) =>            // <-- third request that returns something
    this.http.get('request3')     // <-- use only property `b` from first request
  )
).subscribe({
  next: (result) => {
    console.log(result);          // <-- result from third request
  },
  error: (error) => {
    // handle error
  }
});