Reputation: 1827
Assume I have function which makes http call and returns Observable with user details.
If user doesn't exist it returns Observable which emits error.
// Get user by id
function getUser(id) {
return Rx.Observable.create(obs => {
if (id === 1) {
obs.next('200 - User found');
obs.complete();
} else {
obs.error('404 - User not found');
}
});
}
// This will print "200 - User found" in the console after 2 seconds
getUser(1)
.delay(2000)
.subscribe(r => console.log(r));
// !!! Delay will not work here because error emmited
getUser(2)
.delay(2000)
.subscribe(null, e => console.log(e));
Is there any way to delay Observable which emits error?
Upvotes: 2
Views: 769
Reputation: 105439
I'm curious why Observable doesn't delayed if it returns error
Here is the source code of the delay
operator:
class DelaySubscriber<T> extends Subscriber<T> {
...
protected _next(value: T) {
this.scheduleNotification(Notification.createNext(value)); <-------- notification is scheduled
}
protected _error(err: any) {
this.errored = true;
this.queue = [];
this.destination.error(err); <-------- error is triggered immediately
}
protected _complete() {
this.scheduleNotification(Notification.createComplete());
}
}
Just as with every other operator, delay
subscribes to the source stream - getUser()
in your case - and notifies the listener. You can see from the source code that it doesn't schedule notification when an error occurs and trigger the error
method on the observable immediately.
Here you can learn more about delay
operator.
I want to delay every http request to the API regardless success it or not (to test how app will behave if response is too long)
I recommend using throttle
capabilities of the Chrome Debugging Tools (network tab).
Upvotes: 2