【问题标题】:rxjs timeout: distinguish time expired from source errorrxjs timeout:区分时间过期和源错误
【发布时间】:2020-01-15 17:25:02
【问题描述】:

使用 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,即使它出错了。

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

Playground

【问题讨论】:

    标签: rxjs observable


    【解决方案1】:

    看来您要使用的正确运算符是 timeout 而不是 timeoutWith,我会解释一下。

    timeoutWith 将 - Subscribe to second Observable if no emission occurs in given time span. 这不是你的需要。

    timeout 将 - Error if no value is emitted before specified duration 最适合您的需求/

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

    【讨论】:

      猜你喜欢
      • 2018-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-28
      • 1970-01-01
      • 2012-11-07
      • 2014-01-20
      • 1970-01-01
      相关资源
      最近更新 更多