rxjs 5.5+ retryWhen不调用source observable?

问题描述 投票:0回答:1

我觉得我在这里错过了一些非常简单的东西。我正在尝试为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

所以它只是在重试时重复代码,但是不重复原始的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个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.