如何延迟发出错误的Observable
问题描述:
假设我有函数使http调用并返回Observable与用户的详细信息。如何延迟发出错误的Observable
如果用户不存在,则返回发出错误的Observable。
// 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));
有什么办法来延迟可观察到发射错误?
答
我很好奇,为什么可观察到不延迟,如果返回错误
这里是delay
操作的源代码:
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());
}
}
正如所有其他运营商, delay
在您的案例中订阅源流 - getUser()
- 并通知听众。您可以从源代码中看到它在发生错误时不会安排通知,并立即在observable上触发error
方法。
我不想耽误每一个HTTP请求到API不管成功,或 不(测试应用程序将如何表现,如果响应过长)
我建议使用throttle
能力的Chrome调试的工具(网络选项卡)。
你为什么推迟呢? –
我想延迟对API的每个http请求,无论成功与否(测试应用程序在响应太长时如何表现) –
您正在编写测试吗?你通常应该使用浏览器网络选项卡节流功能来模拟长请求 –