迅速.结合.重试时,有什么方法可以多次调用发布者块? [英] Swift. Combine. Is there any way to call a publisher block more than once when retry?

查看:53
本文介绍了迅速.结合.重试时,有什么方法可以多次调用发布者块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用Swift/Combine的retry()发生某些错误时,我想发出一个以上的网络请求.发布者内部的块仅被调用一次,这意味着在发生错误时仅对真实应用程序发出一个请求.我的代码是:

I want to make a network request more than one time when some error occurs using retry() from Swift/Combine. The block inside the publisher is called once only which means one only one request is made for a real app when error happens. My code is:

import UIKit
import Combine
import PlaygroundSupport

enum TestFailureCondition: Error {
    case invalidServerResponse
}

var backgroundQueue: DispatchQueue = DispatchQueue(label: "backgroundQueue")

var failPublisher: AnyPublisher<(Data, URLResponse), Error> {
    Future<(Data, URLResponse), Error> { promise in
        print("Attempt to call")
        backgroundQueue.asyncAfter(deadline: .now() + Double.random(in: 1..<3)) {
            promise(.failure(TestFailureCondition.invalidServerResponse))
        }
    }
    .eraseToAnyPublisher()
}

let cancellable = failPublisher
.print("(1)>")
.retry(3)
.print("(2)>")
.sink(receiveCompletion: { fini in
    print(" ** .sink() received the completion:", String(describing: fini))


    PlaygroundPage.current.finishExecution()
}, receiveValue: { stringValue in
    print(" ** .sink() received \(stringValue)")
})

PlaygroundPage.current.needsIndefiniteExecution = true

我希望 backgroundQueue.asyncAfter(deadline)在发生某些错误之前被调用三遍.有人知道为什么吗?

I expect that backgroundQueue.asyncAfter(deadline) is called three time before some error happens. Does anyone know why?

推荐答案

我设法通过使用 tryCatch()函数并提出了另一个请求来实现预期的行为:

I managed to achieve the expected behaviour by utilising tryCatch() function and making another request: Link

该链接包含两种实现相同行为的方式,包括上述 Deferred {} .

The link contains two ways to achieve the same behaviour including Deferred {} mentioned above.

这篇关于迅速.结合.重试时,有什么方法可以多次调用发布者块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆