user3818229
user3818229

Reputation: 1617

RxJS: mergeMap operator cancelling other active requests when one of them throws an error

Based on the article I tried to implement parallel update logic with multiple requests to a server:

const prouctIds: number[] = [1, 2, 3];
const requests = from(prouctIds)
    .pipe(mergeMap(id => /* Emulating error when updating some entity*/ throwError(id + '/err')));
requests.subscribe(success => console.log(success), err => console.error('error block', err));

As the author said:

So if there is any request fails i.e. throws server side error, then it doesn't affect other parallel requests.

But in my case if some of the requests returns an error, other active requests are cancelling. If you run the code snippet above, you can notice one error message in console only.

  1. I know that I can use forkJoin with inner catchError pipe, but what then is the difference between these operators if mergeMap also cancels parallel requests if an error occurred in one of them?
  2. How to achieve my goal without using inner catchError pipe and transform the error to a regular observable, i.e. catchError(err => of(err));

Thanks in advance!

Upvotes: 1

Views: 2125

Answers (1)

frido
frido

Reputation: 14089

From the RxJS documentation:

"Error" and "Complete" notifications may happen only once during the Observable Execution, and there can only be either one of them.

In an Observable Execution, zero to infinite Next notifications may be delivered. If either an Error or Complete notification is delivered, then nothing else can be delivered afterwards.
[RxJS Documentation - Observable]

So you can't have an Observable call the error callback multiple times, as the article you posted suggests. You have to use an inner catchError to return an Observable that doesn't error.

Use mergeMap or merge instead of forkJoin if you want to get responses as soon as they arrive because forkJoin only emits when all inner Observables completed.

Upvotes: 1

Related Questions