Skip to content

Instantly share code, notes, and snippets.

@alexpaul
Created August 5, 2020 11:04
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 alexpaul/923a2f82e84f0dbcd3807ad77882ee95 to your computer and use it in GitHub Desktop.
Save alexpaul/923a2f82e84f0dbcd3807ad77882ee95 to your computer and use it in GitHub Desktop.
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