Home > database >  Handle multiple Http request using RxjS
Handle multiple Http request using RxjS

Time:01-20

I have a scenario where I want to first make an HTTP call, and when the response(1) comes I want to make second HTTP call which does not need the response(1), and suppose this second HTTP call gives response(2). Now I want to make multple HTTP calls that would be using data from both response(1) and response(2). How can I acheive this Using RxJS?

CodePudding user response:

I think you should use the concatMap operator plus some tricks to move the response of the first call down to the last calls.

So the code could look like this

firstCall().pipe(
   // use concatMap to make sure you make the second call after the first one completes
   concatMap(resp_1 => {
      return secondCall().pipe(
         // use map here to move both the first and second response down the pipeline
         map(resp_2 => {
           // here we place both responses into an object which is returned by map
           return {resp_1, resp_2}
         })
      ),
      // now it is time to make all other calls once the second call has completed
      // therefore again we use concatMap
      concatMap(({resp_1, resp_2}) => {
         // the function passed to concatMap has to return an Observable
         // I assume these calls can be made in parallel and so I use forkJoin
         // which returns an Observable which notifies as soon as all the 
         // calls have completed
         return forkJoin([thirdCall({resp_1, resp_2}), fourthCall({resp_1, resp_2}), ...])
      })
   })
)
// here you subscribe
.subscribe({
   next: arrayOfResponses => {
      // do something with the array of responses of thirdCall, fourthCall and so on
   }
})

You may find this article interesting as it talks about common patterns of use of RxJs with http calls

CodePudding user response:

There is a handy RxJS operator suitable for this situation. It combines multiple HTTP requests and emits a tuple value when they are all completed. It is called

forkJoin(...args: any[]): Observable<any>

Per https://www.learnrxjs.io/learn-rxjs/operators/combination/forkjoin:

This operator is best used when you have a group of observables and only care about the final emitted value of each. One common use case for this is if you wish to issue multiple requests on page load (or some other event) and only want to take action when a response has been received for all. In this way it is similar to how you might use Promise.all.

Read more about it: https://rxjs.dev/api/index/function/forkJoin

You can also check my answer regarding similar question: RxJS - Combine Two HTTP GET Parallel Requests

  •  Tags:  
  • Related