Skip to content

Instantly share code, notes, and snippets.

@jasdev
Created April 30, 2020 18:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasdev/860b2b8c06fa9d74c82ec51919158390 to your computer and use it in GitHub Desktop.
Save jasdev/860b2b8c06fa9d74c82ec51919158390 to your computer and use it in GitHub Desktop.
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