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 | |
Thanks Stan! I probably could also be wrapped with Deferred so that it only does its work as soon as someone subscribes?! as far as I understand that would be the preferred pattern for Combine. I need to try that with the Dispatch Queue: https://www.apeth.com/UnderstandingCombine/publishers/publishersfuture.html
That's super interesting, I hadn't seen this. In this case, the usage is:
Deferred { requestCatAsync(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)
... 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!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
One adjacent pattern I've found I really like is the
Future
, for making the call asynchronous. It feels very much like theAnyPublisher
, but doesn't rely on the type erasure boilerplate--and makes it easy to add dispatch queue invocations into your code.Good documentation