【问题标题】:RXJS emit immediately and retryRXJS 立即发出并重试
【发布时间】:2019-07-26 19:31:41
【问题描述】:

我们在 Angular 中发出一个 http 请求,该请求返回一些包含布尔值的数据,该布尔值指示数据是否已被完全处理。我们希望从第一个 http 响应中发出不完整的数据,并继续发出 http 请求,直到处理为真。如果第一个响应返回已处理的 true,我们还希望避免重复 http 请求。我们正在使用 retryBackoff 库,如果我理解正确的话,它只是 retryWhen 并带有延迟。

这是我们正在处理的代码示例:

const crashDetails$ = combineLatest(crashId$, database$)
   .pipe(switchMap(([crashId, database]) => { 
        return this._crashDetailsService.getCrashDetails({crashId, database});
    });

const crashDetailsWithRetry$ = crashDetails$
    .pipe(
        tap(crashDetails => {
            if (!crashDetails.processed) {
               throw new Error('Still processing, retry if able');
            }
        }),
        retryBackoff(retryOptions)
    );

return merge($crashDetails, crashDetailsWithRetry$);

问题是在处理为 true 的情况下会发出 2 个请求。

我尝试将 share() 和 shareReplay(1) 添加到 crashDetails$,但这会导致 crashDetailsWithRetry$ 停止工作。有没有一种简单的方法来实现我们想要的,或者我应该创建一个新的主题和自定义重试逻辑来处理这种情况?

谢谢!

【问题讨论】:

    标签: javascript angular typescript rxjs


    【解决方案1】:

    这只是一个条件轮询方案:

     const crashDetails$ = combineLatest(crashId$, database$)
       .pipe(switchMap(([crashId, database]) => { 
            // switch into a timer that switches into your observable, take while processing
            return timer(0, 3000).pipe( // set 3000 to whatever ms interval you want to poll on
              switchMapTo(this._crashDetailsService.getCrashDetails({crashId, database}),
              takeWhile(details => !details.processed, true) //take while not processed
            );
        });
    
     return crashDetails$;
    

    【讨论】:

    • 每次我们轮询 API 时都会发出这个信号吗?目标是在每次轮询时发出未处理的结果,最后在最后发出处理后的结果,从而结束轮询循环
    • 是的,只要它在间隔内完成,它就会发出每个调用,您可以使用mergeMapTo 来保证无论花费多长时间它们都会发出
    • 谢谢,这让我找到了正确的位置。请注意,该解决方案需要 rxjs v6.4+ 和 inclusive 标志。我们还最终使用了 intervalBackoff 而不是 timer 请求之间的指数延迟。 codesandbox.io/s/njguf
    • 没错,忘了包含部分,因为那是新的。很高兴它有帮助。您还可以通过添加 delayWhen 运算符来实现回退效果
    猜你喜欢
    • 1970-01-01
    • 2022-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-11-19
    • 2016-08-28
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多