Search code examples
typescriptrxjssubscriptionrxjs-observables

Rxjs notify when all http requests finish with error handling for each request


Hi I have some class objects to POST and I need to store the result back into them, e.g.:

class Bid {
    price: number;
    result?: string;
}
const bids: Bid[] = [{price: 10},{price:20}];
for (const bid of bids) {
    http.post(bid).subscribe(
        r => bid.result = r,
        e => bid.result = "error:" + e
    );
}

So far so good, but now I want to be notified when all POSTs return, as if I am forkjoining all the POSTs and subscribe to that, then do something when they all complete.

Different from forkjoin is I need to do error handling in each POST subscription.

I wonder how that can be done as I also need to subscribe to each POST to store the result in each corresponding source class object.


Solution

  • If I understand this right, a combination of

    • tap to store the result in each object and manage errors for each post
    • catchError to avoid error propagation
    • forkJoin to glue the posts together

    should work.

    A solution could be along these lines

    class Bid {
        price: number;
        result?: string;
    }
    const bids: Bid[] = [{price: 10},{price:20}];
    
    const posts = bids.map(bid => {
       return http.post(bid).pipe(
         // taps accepts an Observer as parameter
         tap({
           next: res => bid.result = r,
           error: e => bid.result = "error:" + e
         }),
         // catch the error and return something that signals the error occurence
         catchError(err => of('Error'))
       )
    })
    
    forkJoin(posts).subscribe({
       next: data => {// data is an array containing either the result or the error }
       complete: () => console.log('I am Done')
    })