Reputation: 26084
I want to emit an error if a method's execution takes more time than a defined timeout. I have tried this (ES6):
getExec() {
return _getObs().timeout(5000, new Error("timeout reached")); //5s timeout
}
_getObs() {
return rx.Observable.create((sub) => {
sub.onNext(executeVerySlowMethod());
sub.onCompleted();
});
}
When I subcribe to getExec
, it doesn't raise any error. What am I doing wrong? (executeVerySlowMethod
is a really slow method that takes more than 5 secs)
Upvotes: 1
Views: 1235
Reputation: 1883
This is the new way to do it: (RxJS6)
import { of, TimeoutError, throwError } from 'rxjs';
import { timeout, catchError } from 'rxjs/operators';
of(executeVerySlowMethod()).pipe(
timeout(5000),
catchError(err => {
if (err instanceof TimeoutError) {
throw new Error('timeout reached');
}
return throwError(err);
}))
Upvotes: 2
Reputation: 9425
There is no overload of .timeout()
available which takes a custom Error. This was removed in RxJs5. Your code will error because the second argument is expected to be of type Scheduler|null
.
Also; creating an observable to wrap your function can be done easier by just using Observable.of(executeVerySlowMethod())
which is less error-prone.
Observable
.of(executeVerySlowMethod())
.timeout(5000)
should do the trick UNLESS executeVerySlowMethod()
is blocking // sync.
Upvotes: 3