rxjs - rxjs timeout:区分时间过期和源错误
问题描述
使用 RxJS 6.5,我订阅了一个流,我想采取两个不同的操作: - 一个是源错误时 - 另一个是源需要很长时间才能发送数据(超时)
这是我目前拥有的
source$.pipe(
timeoutWith(5000, log('timeout!')),
catchError(log('error!'))
).subscribe();
function log(msg) {
console.log(msg);
return of(null);
}
当我的源发出的时间超过 5000 毫秒时,我得到了预期的结果:超时!
但是,当我的源提前(在 5000 毫秒之前)抛出错误时,两条线都会执行。似乎timeoutWith
只要源没有发出,它就会被触发,即使它出错了。
如何设置管道,以便超时逻辑仅在实际时间已过时运行,而不是因为流因错误而中止?
解决方案
看起来您使用的正确运算符 istimeout
而不是,timeoutWith
我会解释。
timeoutWith
will -如果在给定的时间跨度内没有发射,则订阅第二个 Observable。这不是你的需要。
timeout
will -如果在最适合您需要的指定持续时间之前没有发出任何值,则会出错/
在您的管道中使用timeout
应该如下所示:
source$.pipe(
catchError(() => log('func error!')), // will log only when your source throws an error
timeout(5000),
catchError(() => log('timeout error!')) // will log only if your source as timed-out for 5000
).subscribe();
推荐阅读
- java - 以编程方式更改语言环境不适用于 Android 6.0.1
- nameko - 实现(抽象)Nameko 服务继承
- html - 在 CSS 中 ID 末尾带有奇数/偶数的目标 div
- php - 如何预览和下载超过 12 MB 的 php 文件?
- c# - 带有 Web API 的角度
- mongodb - 查找和展开mongodb后如何防止重复总和
- java - POST 请求适用于 POSTMAN,但不适用于我的 Java 应用程序
- docker - 启动容器时如何获取docker容器id
- javascript - 如何从 JSON 中获取对象,然后将它们用于我的站点?
- python - 如何为模型中的特定字段创建自定义权限?