-
-
Save jasdev/7015fbb8388203fc5d111b9c857f7693 to your computer and use it in GitHub Desktop.
Cold publisher double `Sink` with distinct subscribers.
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
import PlaygroundSupport /// (1) We’ll need this import to allow for indefinite execution. | |
PlaygroundPage.current.needsIndefiniteExecution = true | |
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 sink1 = Subscribers.Sink<[Photo], Error>( | |
receiveCompletion: { print("1: \($0)") }, | |
receiveValue: { print("1: \($0.map(\.id))") } | |
) | |
let sink2 = Subscribers.Sink<[Photo], Error>( | |
receiveCompletion: { print("2: \($0)") }, | |
receiveValue: { print("2: \($0.map(\.id))") } | |
) | |
coldPublisher | |
.subscribe(sink1) | |
DispatchQueue.main.asyncAfter(deadline: .now() + 2) { /// (2) Tacking on some delay to make things more clear. | |
coldPublisher | |
.subscribe(sink2) | |
} | |
/// (3) Output: | |
/// ```none | |
/// 1: failure(__lldb_expr_55.SomeError.anError) | |
/// 2: ["0", "1", "10", "100", "1000", "1001", "1002", "1003", "1004", "1005", "1006", "1008", "1009", "101", "1010", "1011", "1012", "1013", "1014", "1015", "1016", "1018", "1019", "102", "1020", "1021", "1022", "1023", "1024", "1025"] | |
/// 2: finished | |
/// ``` |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment