【问题标题】:rxjs 5.5+ retryWhen not calling source observable?rxjs 5.5+ retryWhen not call source observable?
【发布时间】:2019-02-12 00:20:28
【问题描述】:

我觉得我在这里错过了一些非常简单的东西。我正在尝试为 fetch 创建一个简单的重试,但只有 retryWhen 中的代码正在执行。我正在使用 React,所以我没有 this.http.get 的便利。也许这是from(/*promise*/) 的问题?我试图将重试逻辑基于this post

这是我希望看到的:

Getting data from fetch...
In the retryWhen
In the interval
/* repeat the previous 3 lines 3x times including the Fetch */
Giving up

相反,我得到:

Getting data from fetch...
In the retryWhen
In the interval...
In the interval...
In the interval...
In the interval...
Giving up

所以它只是重复他 retryWhen 间隔中的代码,而不是重复原始的 fetchData 调用。我可能遗漏了一些对我的 RXJS 知识很重要的东西。

这是测试代码:

const fetchData = new Promise((res, rej) => {
  console.log("Getting data from fetch...");
  rej(); // just fail immediately to test the retry
});

const source = from(fetchData)
  .pipe(
    retryWhen(_ => {
      console.log("In the retryWhen");
      return interval(1000).pipe(
        tap(_ => console.log("In the interval...")),
        flatMap(count => count == 3 ? throwError("Giving up") : of(count))
      )
    }));

source.subscribe(
  result => console.log(result),
  err => console.log(err)
);

【问题讨论】:

    标签: rxjs observable rxjs6 rxjs-pipeable-operators retrywhen


    【解决方案1】:

    更改下面的代码看看它是否有效。 retryWhen 向您传递一个错误流,如果出现错误,它将继续发出。您返回一个timer 以指定retryWhen 内每次重试之间的延迟。延迟后它将为您重试可观察的源

    const fetchData = defer(() => new Promise((res, rej) => {
          console.log('in promise')
            rej("Failed to fetch data"); 
          // fail the first 2 times
        }) );
    
    const source = fetchData.pipe(
      retryWhen(err => {
        let count = 0;
        console.log("In the retryWhen");
        return err.pipe(
          tap(_ => {
            count++;
            console.log("In the interval...");
          }),
          mergeMap(_ => (count == 2 ? throwError("Giving up") : timer(2000)))
        );
      })
    );
    
    source.subscribe(result => console.log(result), err => console.warn(err));
    

    https://codepen.io/fancheung/pen/gqjawe

    【讨论】:

    • 谢谢,我在控制台中得到了相同的结果,但修改后的代码。我创建了一个 stackblitz 来显示结果:stackblitz.com/edit/typescript-us8viy
    • 这里有一个更简单但不起作用的例子。这只是一个简单的retry,永远不会重试。我在这里想念什么? stackblitz.com/edit/typescript-hfcdyq
    • 忘记改defer了,promise会立即执行,不会重复。更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-08-12
    • 1970-01-01
    • 2019-01-20
    • 2021-04-28
    • 2018-12-26
    • 2017-03-01
    • 2020-02-26
    相关资源
    最近更新 更多