I need a timeout operator to throw an error when parameter isTimeoutNeeded is True, so that I could handle the case if the subscribed observable do not emit any value after X seconds.
if (isTimeoutNeeded) {
this.service.getData()
.pipe(
timeout(10000),
...
)
.subscribe((...) => ...);
} else {
this.service.getData()
.pipe(
...
)
.subscribe((...) => ...);
}
Is it possible to write this in a rxjs way by conditionally adding timeout operator when needed?
I have tried using iif and switchMap but it did not work.
this.service.getData()
.pipe(
mergeMap((response) =>
iif(() => !isTimeoutNeeded,
of(response),
of(response).pipe(timeout(10000)) // did not apply timeout if isTimeoutNeeded = True
)
)
.subscribe((...) => ...);
switchMap
this.service.getData()
.pipe(
switchMap((response) => {
if (!isTimeoutNeeded) {
return of(response);
}
return of(response).timeout(10000); // did not apply timeout if isTimeoutNeeded = True
})
.....
)
)
.subscribe((...) => ...);