If, like me, you’re a bit late to the game with Combine, here’s a very simple way to get started:
Firstly, here’s your data source which may be a singleton (that’s up to you):
import Combine
class FooManager {
static let shared = FooManager()
@Published var bar: String?
}
The @Published
means that you can access this var like any other one: simply get or set its value using FooManager.shared.bar
. However it automatically also creates a $bar
Combine publisher.
Now in a VC, you can bind this value to a label like so:
class ViewController: UIViewController {
// When this is released when the VC is freed,
// it automatically frees all the bindings.
var cancellables: [AnyCancellable] = []
@IBOutlet weak var myLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Cancellables retains the Combine binding.
// The binding retains 'myLabel'.
// So don't assign on 'self', or you'll have a
// retain cycle memory leak eg: VC -> Cancellables -> Binding -> VC.
FooManager.shared
.$bar // Automagically generated by @Published.
.assign(to: \.text, on: myLabel) // Retains 'myLabel'.
.store(in: &cancellables) // cancellables keeps the binding alive.
If you don’t want to use ‘assign’, you may use ‘sink’ like so:
FooManager.shared
.$bar
.sink(receiveValue: { [weak self] value in
self?.myLabel.text = value
})
.store(in: &cancellables)
So now you know how to start using Combine. Please be careful not to overdo it!
Photo by Luke Thornton on Unsplash
Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.
(Comp Sci, Hons - UTS)
Software Developer (Freelancer / Contractor) in Australia.
I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!
Get in touch:
[email protected]
github.com/chrishulbert
linkedin