gpt4 book ai didi

angular - 如何创建具有延迟和限制尝试的 RXjs RetryWhen

转载 作者:太空狗 更新时间:2023-10-29 16:51:27 27 4
gpt4 key购买 nike

我正在尝试进行 API 调用(使用 angular4),它会在失败时使用 retryWhen 重试。我希望它延迟 500 毫秒并重试。这可以通过以下代码实现:

loadSomething(): Observable<SomeInterface> {
return this.http.get(this.someEndpoint, commonHttpHeaders())
.retryWhen(errors => errors.delay(500));
}

但这会一直尝试下去。我如何将其限制为 10 次?

谢谢!

最佳答案

您需要对重试信号应用限制,例如,如果您只想重试 10 次:

loadSomething(): Observable<SomeInterface> {
return this.http.get(this.someEndpoint, commonHttpHeaders())
.retryWhen(errors =>
// Time shift the retry
errors.delay(500)
// Only take 10 items
.take(10)
// Throw an exception to signal that the error needs to be propagated
.concat(Rx.Observable.throw(new Error('Retry limit exceeded!'))
);

编辑

一些评论者询问如何确保最后一个错误被抛出。答案有点不那么清晰,但功能同样强大,只需使用一种扁平化 map 运算符(concatMap、mergeMap、switchMap)来检查您所在的索引。

注意:使用新的 RxJS 6 pipe 语法进行 future 验证(这在 RxJS 5 的更高版本中也可用)。

loadSomething(): Observable<SomeInterface> {
const retryPipeline =
// Still using retryWhen to handle errors
retryWhen(errors => errors.pipe(
// Use concat map to keep the errors in order and make sure they
// aren't executed in parallel
concatMap((e, i) =>
// Executes a conditional Observable depending on the result
// of the first argument
iif(
() => i > 10,
// If the condition is true we throw the error (the last error)
throwError(e),
// Otherwise we pipe this back into our stream and delay the retry
of(e).pipe(delay(500))
)
)
));

return this.http.get(this.someEndpoint, commonHttpHeaders())
// With the new syntax you can now share this pipeline between uses
.pipe(retryPipeline)
}

关于angular - 如何创建具有延迟和限制尝试的 RXjs RetryWhen,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44911251/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com