After a solid iOS developer?

I am an iOS developer / freelancer / contractor based in Australia.
I specialise in building well-structured app platforms for companies to build their long-term app strategies upon.
I have a broad array of experience from my work at Google, News Corp, Fox Sports, NineMSN, FetchTV, Woolworths, and Westpac.
Please see my portfolio, then get in touch if I can be of service!

See my Portfolio »

Combine

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


You can read more of my blog here in my blog archive.

Chris Hulbert

(Comp Sci, Hons - UTS)

iOS Developer (Freelancer / Contractor) in Australia.

I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Woolworths, 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
my resume



 Subscribe via RSS