Swift. Combine. Is there any way to call a publisher block more than once when retry?
Future
runs its body once, as soon as it is created, even if nothing subscribes to it. It saves the result and completes all subscriptions with that same result. So using the retry
operator on a Future
won't make the Future
run its body again on failure.
You want each subscription to run the body again. You can do that by wrapping your Future
in a Deferred
. The Deferred
will create a new Future
for every subscription.
var failPublisher: AnyPublisher<(Data, URLResponse), Error> {
Deferred {
Future<(Data, URLResponse), Error> { promise in
print("Attempt to call")
backgroundQueue.asyncAfter(deadline: .now() + Double.random(in: 1..<3)) {
promise(.failure(TestFailureCondition.invalidServerResponse))
}
}
}
.eraseToAnyPublisher()
}
I managed to achieve the expected behaviour by utilising tryCatch()
function and making another request: Link
The link contains two ways to achieve the same behaviour including Deferred {}
mentioned above.