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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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

1
2
3
4
5
6
7
8
9
10
11
12
13
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

1
2
3
4
5
6
7
override func viewDidLoad() {
super.viewDidLoad()

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

Comments