MVVM and data binding
While data binding and two-way data binding are not required to use MVVM, you saw in the previous example that binding actions and values is tedious, a source of boilerplate, and prone to errors.
While data binding is usually found in Reactive programming frameworks, it revolves around a simple object: the Observable
object. The responsibility of an observable is to call the observers whenever a change in the internal value occurs.
Implementing the Observable class
We'll implement Observable
as a generic class, as it should be able to wrap any kind of object:
class Observable<Type> { typealias Observer = (Type) -> () typealias Token = NSObjectProtocol private var observers = [(Token, Observer)]() var value: Type { didSet { notify() } } init(_ value: Type) { self.value = value } @discardableResult func bind(_ observer: @escaping Observer) -> Token { defer { observer(value) } ...