I'm a rookie in rxjs, and I'm trying to figure out what happened in the following code.
Indeed, in order to illustrate the idea, I prepare two simple promises (resolvePromise and rejectPromise), one resolves a promise, and the other rejects. A "Subject" instance is used to trigger these two promises (piped with mergeMap and forkJoin). At the end, two separates instructions (source$.next('xxx')) are added, hoping to trigger the subscription twice.
But finally, only the first "source$.next('1')" triggers the subscription, and the next "source$.next('2')" seems to do nothing.
I guess this behavior is caused by the reject promise, which literally "throws an exception". But I'm wondering how can I fix this code, so that the second "source$.next('2')" will also trigger the subscription.
Thanks a lot
import { of,forkJoin,Subject } from 'rxjs';
import { mergeMap } from 'rxjs/operators';
const resolvePromise = val =>
new Promise(resolve => resolve(`resolve value: ${val}`));
const rejectPromise = err =>
Promise.reject(`reject error: ${err}`);
const source$ = new Subject();
source$
.pipe(mergeMap(val => {
return forkJoin([
resolvePromise(val),
rejectPromise(val)
]);
}))
.subscribe(
console.log,
console.error
);
source$.next('1');
source$.next('2');
Update
Based on suggestion given by Andrei Gătej below, in order to overcome this problem, I chose to pipe a catchError after the forkJoin, and place the error handling inside.
source$.pipe(
mergeMap(val => {
return forkJoin([
resolvePromise(val),
rejectPromise(val)
])
.pipe(
catchError(err => {
// your error handling business logic
console.error(err);
return empty();
})
);
}))
.subscribe(console.log);