Created
April 30, 2020 18:28
-
-
Save jasdev/860b2b8c06fa9d74c82ec51919158390 to your computer and use it in GitHub Desktop.
Cold publisher Sink attempt after failure.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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