Skip to content

Instantly share code, notes, and snippets.

@denisenepraunig
Created December 23, 2020 14:03
Show Gist options
  • Save denisenepraunig/5ad02374b78977a8bff01256d47ef624 to your computer and use it in GitHub Desktop.
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.
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
@denisenepraunig
Copy link
Author

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

@sstadelman
Copy link

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