Created
August 5, 2020 11:04
-
-
Save alexpaul/923a2f82e84f0dbcd3807ad77882ee95 to your computer and use it in GitHub Desktop.
Publishers and Subscribers in Combine.
This file contains hidden or 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 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