首页 > 解决方案 > 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只要源没有发出,它就会被触发,即使它出错了。

如何设置管道,以便超时逻辑仅在实际时间已过时运行,而不是因为流因错误而中止?

操场

标签: rxjsobservable

解决方案


看起来您使用的正确运算符 istimeout而不是,timeoutWith我会解释。

timeoutWithwill -如果在给定的时间跨度内没有发射,则订阅第二个 Observable。这不是你的需要。

timeoutwill -如果在最适合您需要的指定持续时间之前没有发出任何值,则会出错/

在您的管道中使用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();

StackBlitz 演示


推荐阅读