I sent the below code snippet for code review. This effect needs to dispatch a success action after a request call, or an error action if the service method throws an error, so pretty standard.
@Effect()
fetchData$ = this.actions$.pipe(
ofType(ActionTypes.FetchData),
switchMap(() => {
return this.dataService.fetchData().pipe(
map((data: IData): StoreAction<IData> =>
new FetchDataSuccess(data)),
catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
)};
));
However, I was given a comment by an external developer (that I have no contact with and therefore cannot ask for clarification). He instructed me to wrap my switchMap with another switchMap (like i the code below), because the catch error inside the first switchMap in my above code 'would cause the effect to break'.
@Effect()
fetchData$ = this.actions$.pipe(
switchMap((a: StoreAction<IType>) => of(a).pipe(
ofType(ActionTypes.FetchData),
switchMap(() => {
return this.dataService.fetchData().pipe(
map((data: IData): StoreAction<IData> =>
new FetchDataSuccess(data)),
);
}),
catchError((error) => of(addErrorValue(error, ErrorCode.FETCH_DATA)))
))
);
Now, I read up on catching errors in effects and my understanding is catchErrors need to be wrapped in switchMap because then the effect wont break because the failed inner (as opposed to outer) observable will just be replaced with a successful one and the effect observable can be forced into a success state eventually (if I understand it correctly).
What I don't understand and what I'm missing is: Why are we wrapping the switchMap into ANOTHER switchMap? Can someone please explain the workflow of this particular observable in the first case vs. the second?