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.
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
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
override func viewDidLoad() {
super.viewDidLoad()
viewModel.friends.bind { friends in
self.friendsCountLabel.text = "\(friends.count)"
}
}