rxjs 5.5+ retryWhen not calling source observable?

rxjs 5.5+ retryWhen not calling source observable?

我觉得我在这里遗漏了一些非常简单的东西。我正在尝试为获取创建一个简单的重试,但只有 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

所以它只是在重试时重复代码,而不是重复原来的 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)
);

更改下面的代码看看它是否有效。 retryWhen 传递给您一个错误流,如果有错误,它将继续发出。你 return 一个 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