Encountered a puzzling rxjs issue that has me stumped. Here's the scenario: I have two requests to handle:
const obs1$ = this.http.get('route-1')
const obs2$ = this.http.get('route-2')
If obs1$
throws an error, I want to catch it and emit a static value instead. However, if obs1$
completes successfully, I want to switch over to obs2$
without catching any errors from it. Currently, my solution looks like this:
obs1$.pipe(
catchError(() => of('my value')),
switchMap((v) => v === 'my value' ? of(v) : obs2$)
).subscribe(
(v) => console.log(v, 'got my result'),
(e) => console.log(e, 'encountered an error')
)
Although this works, it feels a bit convoluted. I'm curious if there's a cleaner way to achieve the same outcome. I've ruled out moving the catchError
after switchMap
as it would also catch errors from obs2$
, which is not ideal. Ideally, I'd like to bypass to the end if an error occurs with obs1$
.