【问题标题】:How to delay throwError with RxJS?如何用 RxJS 延迟 throwError?
【发布时间】:2019-10-08 15:03:22
【问题描述】:

如预期的那样,以下代码在 5 秒后发出 42:

const valueObservable = of(42).pipe(delay(5000));
valueObservable.subscribe((value) => console.log(value));

但是,订阅时会立即抛出版本错误:

const throwingObservable = throwError(new Error('My Error')).pipe(delay(5000));
throwingObservable.subscribe((value) => console.log(value), (error) => console.error(error));

为什么会这样?如何延迟抛出错误?

【问题讨论】:

    标签: rxjs rxjs6


    【解决方案1】:

    Rxjs 错误是异常,它会立即停止流并让您捕获它以对意外事件做出反应。我猜你除了catchError

    之外没有办法操作 throwError 流

    解决方案 1:在抛出错误之前操作流。

    const throwingObservable = throwError(new Error('My Error'));
    timer(5000).pipe(mergeMap(e => throwingObservable))
      .subscribe((value) => console.log(value), (error) => console.error(error));
    

    解决方案 2:捕获错误,延迟流,然后再次调度它

    throwingObservable.pipe(
      // We catch the error, we delay by adding timer stream, then we mergeMap to the error.
      catchError(e => timer(1000).pipe(mergeMap(t => throwError(e)))
    )).subscribe(console.log, console.error);
    

    You can see it in action

    【讨论】:

      【解决方案2】:

      我找到了一种 (IMO) 更简单的方法来延迟抛出错误:

      const throwingObservable = of(42).pipe(
          delay(5000),
          switchMap(() => throwError(new Error('My Error')))
      );
      throwingObservable.subscribe(
          value => console.log(value),
          error => console.error(error)
      );
      

      【讨论】:

        【解决方案3】:

        我遇到了类似的问题,发现了这个 github 问题:https://github.com/Reactive-Extensions/RxJS/issues/648

        更新到我的用例会是这样的:

        const throwingObservable = throwError(new Error('My Error'))
          .pipe(
            materialize(),
            delay(4000),
            dematerialize()
          );
        
        throwingObservable.subscribe(console.log, console.error);
        

        延迟 4 秒后抛出

        【讨论】:

        • 哈,这是对原本鲜为人知的一对运算符的非常聪明的用法。
        猜你喜欢
        • 1970-01-01
        • 2018-10-17
        • 2019-04-04
        • 1970-01-01
        • 1970-01-01
        • 2017-07-27
        • 2018-08-31
        • 2017-05-15
        • 1970-01-01
        相关资源
        最近更新 更多