如何在自定义运算符中引发流错误?

时间:2018-07-27 07:19:53

标签: rxjs rxjs6

我找到了要使用的cstom运算符。

这是一个重试http请求的运算符。代码来自Stephen Fluin:https://github.com/StephenFluin/http-operators/blob/master/operators/retryExponentialBackoff.operator.ts

问题是,如果在完成所有这些重新绑定后,它没有将错误放入流中,则仅完成。 我希望它引发错误。怎么做? 我认为这部分应该修改:

     error(err: any) {
        if (count <= maxTries) {
          subscription.add(scheduler.schedule(subscribe, initialWait * Math.pow(2, count++)));
        }
      },

这是整个操作员的课程

/**
 * Repeats underlying observable on a timer
 *
 * @param maxTries The maximum number of attempts to make, or -1 for unlimited
 * @param initialWait Number of seconds to wait for refresh
 */
export const retryExponentialBackoff = (
  maxTries = -1,
  initialWait = 1,
  scheduler: SchedulerLike = asyncScheduler
) => <T>(
  source: Observable<T>
) => {
  return new Observable<T>(subscriber => {
    let count = 1;
    const subscription = new Subscription();

    const subscribe = () =>
      subscription.add(
        source.subscribe({
          next(value: T) {
            count = 1;
            subscriber.next(value);
          },
          error(err: any) {
            if (count <= maxTries) {
              subscription.add(scheduler.schedule(subscribe, initialWait * Math.pow(2, count++)));
            }
          },
          complete() {
            subscriber.complete();
          },
        })
      );

    subscribe();

    return subscription;
  });
};

1 个答案:

答案 0 :(得分:2)

我会像这样尝试向用户添加冒泡的错误:

error(err: any) {
  if (count <= maxTries) {
    subscription.add(scheduler.schedule(subscribe, initialWait * Math.pow(2, count++)));
  }
  else {
    subscriber.error(err);
  }
},

因此,在您的maxTries计数用完之后,该错误就会向下游发出。