Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Publishers and Subscribers in Combine.
import Foundation
import Combine
let publisherArr = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0].publisher
// publisher is of type Publishers.Sequence<[Double], Never>
// the generic type here takes two arguments <Output, Failure>
// in this case the our publisherArr will "Never" fail.
// there are many publishers that can fail, take for example the URLSession.shared.dataTaskPublisher
// the Output is <Data, URLResponse>
// the Failuer is URLError
let dataTaskPublisher = URLSession.shared.dataTaskPublisher(for: URL(string: "alexpaul.dev")!)
publisherArr
.sink(receiveCompletion: { (completion) in
print(completion)
}) { (cohort) in
print("received value: \(cohort)")
}
// above we use .sink to subscribe to the values emitted from the publisherArr
// playground output:
/*
received value: 1.0
received value: 2.0
received value: 3.0
received value: 4.0
received value: 5.0
received value: 6.0
finished
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment