RxJS array of HTTP observables: fire next only after previous completes

1k views Asked by At

I have an array of observables (HTTP POST requests) that I need to send off to an API after a specific event. The following is a simplified example of the approach, where I use concat so I can leverage success, error and complete callbacks.

// build up an array of stored POST requests to fire off later
// array is indeterminate length, could be 1 request could be 1,000
let requests = [ req1, req2, req3, req4 ];

concat(...requests).subscribe(
  success => ... handle success ...
  error => ... handle error ...
  () => ... handle completion ...
);

The issue is the concat basically sends all the requests at once, raising the potential for concurrency issues in the API consuming the requests. This issue should be resolved if I am able to fire the requests off one-by-one rather than all at once. I've determined that a forEach loop is not an option.

Is there an RxJS approach such that req2 only emits after req1 completes and req3 emits only after req2 completes and so on? I've been reviewing the RxJS docs but have yet to find anything that fits this scenario.

1

There are 1 answers

2
Michael D On

You could use RxJS from function and higher order mapping operator concatMap.

Try the following

from(requests).pipe(
  concatMap(req => req)
).subscribe(
  success => ... handle success ...
  error => ... handle error ...
  () => ... handle completion ...
);

Without the concatMap operator the request elements of the array would be verbatim emitted as observables instead of being triggered. You could find differences b/n higher order mapping operators in my other answer here.