gpt4 book ai didi

ios - 延迟后组合框架重试?

转载 作者:行者123 更新时间:2023-12-01 15:30:15 25 4
gpt4 key购买 nike

我知道如何使用 .retry直接,在出错后重新订阅,如下所示:

    URLSession.shared.dataTaskPublisher(for:url)
.retry(3)

但这似乎非常简单。如果我认为如果我等待一段时间这个错误可能会消失怎么办?我可以插入 .delay运算符,但即使没有错误,延迟也会运行。而且似乎没有办法有条件地应用运算符(即仅在出现错误时)。

我知道如何通过从头开始编写 RetryWithDelay 运算符来解决这个问题,而且确实这样的运算符是由第三方编写的。但是有没有办法说“如果有错误延迟”,纯粹使用我们给定的运算符?

我的想法是我可以使用 .catch , 因为它的函数只有在出现错误时才会运行。但是函数需要返回一个发布者,我们会使用哪个发布者呢?如果我们返回 somePublisher.delay(...)后跟 .retry ,我们将申请 .retry给错误的出版商,不是吗?

最佳答案

这是 Using Combine 上的一个话题项目 repo 一段时间 - 整个线程:https://github.com/heckj/swiftui-notes/issues/164 .

多头和空头是我们做了一个例子,我认为它可以满足您的需求,尽管它确实使用 catch :

let resultPublisher = upstreamPublisher.catch { error -> AnyPublisher<String, Error> in
return Publishers.Delay(upstream: upstreamPublisher,
interval: 3,
tolerance: 1,
scheduler: DispatchQueue.global())
// moving retry into this block reduces the number of duplicate requests
// In effect, there's the original request, and the `retry(2)` here will operate
// two additional retries on the otherwise one-shot publisher that is initiated with
// the `Publishers.Delay()` just above. Just starting this publisher with delay makes
// an additional request, so the total number of requests ends up being 4 (assuming all
// fail). However, no delay is introduced in this sequence if the original request
// is successful.
.retry(2)
.eraseToAnyPublisher()
}

这是引用 retry pattern I have in the book/online ,这基本上就是你所描述的(但不是你所问的)。

person I was corresponding with on the issue在该线程中提供了一个变体作为扩展,这也可能很有趣:

extension Publisher {
func retryWithDelay<T, E>()
-> Publishers.Catch<Self, AnyPublisher<T, E>> where T == Self.Output, E == Self.Failure
{
return self.catch { error -> AnyPublisher<T, E> in
return Publishers.Delay(
upstream: self,
interval: 3,
tolerance: 1,
scheduler: DispatchQueue.global()).retry(2).eraseToAnyPublisher()
}
}
}

关于ios - 延迟后组合框架重试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60624851/

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