Created
December 23, 2020 14:03
-
-
Save denisenepraunig/5ad02374b78977a8bff01256d47ef624 to your computer and use it in GitHub Desktop.
My very first and very simple example on how to use write some simple Combine concepts from scratch end to end. Can run in a Playground.
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 | |
var storage = Set<AnyCancellable>() | |
struct Cat: Codable { | |
let name: String | |
let age: Int | |
} | |
func requestCat(_ cat: Cat) -> AnyPublisher<Data, Never> { | |
// no error handling - just demo purposes | |
let data = try! JSONEncoder().encode(cat) | |
return Just(data) | |
.eraseToAnyPublisher() | |
} | |
let cat = Cat(name: "Gloria", age: 2) | |
requestCat(cat) | |
.decode(type: Cat.self, decoder: JSONDecoder()) | |
.map { $0.name } | |
.sink { completion in | |
print("completed: \(completion)") | |
} receiveValue: { name in | |
print("cat's name is \(name)") | |
}.store(in: &storage) | |
// prints: | |
// cat's name is Gloria | |
// completed: finished | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's super interesting, I hadn't seen this. In this case, the usage is:
... I'm not sure I like that--there's no strong enforcement that the developer doesn't use the function directly instead of wrapping.
Cool!