How can you make multiple HttpClient requests in order and emit only one value to the subscription?
Let’s assume we want to make a series of POST requests in sequential order and have a subscription that receives a value emitted only after all of the requests completed. The use case could be a scenario where the number of requests is dynamic. Let’s say a user select’s a number a options in a select list, and for each one an update request should be made. Due to specific API requirements the updates cannot be made in parallel, but need to be made sequentially.
The RxJS “concat” operator provides the requirement of sequential order:
“Subscribe to observables in order as previous completes“.
To only emit one final result, the “toArray” operator comes to the rescue:
“Collects all source emissions and emits them as an array when the source completes.”
A final implementation might look like the following:
updateItems(ids: string[]) { const observables = ids.map((id: string) => this.httpClient.post('/items/' + id, {accept: true}) ); return concat(...observables).pipe(toArray()); }