Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cold publisher Sink attempt after failure.
enum SomeError: Error {
case anError
}
let requestURL = URL(string: "https://picsum.photos/v2/list")!
struct Photo: Decodable {
var id: String
}
var attemptCount = 1
let coldPublisher: AnyPublisher<[Photo], Error> = URLSession.shared
.dataTaskPublisher(for: requestURL)
.map(\.data)
.decode(type: [Photo].self, decoder: JSONDecoder())
.tryMap {
defer { attemptCount += 1 }
if attemptCount.isMultiple(of: 2) {
return $0
} else {
throw SomeError.anError
}
}
.eraseToAnyPublisher()
let sink = Subscribers.Sink<[Photo], Error>( /// (1) `Sink` implicitly requests unlimited demand.
receiveCompletion: { print($0) },
receiveValue: { print($0.map(\.id)) }
)
coldPublisher
.subscribe(sink)
coldPublisher
.subscribe(sink)
/// (2) Output, only the first failure logged and the second attempt is ignored:
/// ```none
/// failure(__lldb_expr_47.SomeError.anError)
/// ```
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment