How to make simple Binding in MVVM in iOS

Issue #103

If you use MVVM or any other kinds of helper classes, then there’s need to report back the result to the caller. In simple cases, without asynchronous chaining, RxSwift is a bit overkill, you can just implement your own Binding. Basically, it is just observer pattern, or closure in its simplest form.

swift
class Binding<T> {
  var value: T {
    didSet {
      listener?(value)
    }
  }

  private var listener: ((T) -> Void)?

  init(value: T) {
    self.value = value
  }

  func bind(_ closure: @escaping (T) -> Void) {
    closure(value)
    listener = closure
  }
}

Then you can declare it like

swift
class ViewModel {
  let friends = Binding<[User]>(value: [])

  init() {
    getFacebookFriends {
      friends.value = $0
    }
  }

  func getFacebookFriends(completion: ([User]) -> Void) {
  	// Do the work
  }
}

Finally, this is how you listen to the result via callback

swift
override func viewDidLoad() {
  super.viewDidLoad()

  viewModel.friends.bind { friends in
    self.friendsCountLabel.text = "\(friends.count)"
  }
}
Written by

I’m open source contributor, writer, speaker and product maker.

Start the conversation