Using Observables with ViewModels
The Observable and Binding protocols help to reduce the boilerplate that's necessary when binding a particular view or control to the viewModel's properties.
Let's suppose that we have a simple form for registering users, with their name, password, and age. It can be represented with the following ViewModel:
class SignupViewModel {
var username = Observable<String?>(nil)
var email = Observable<String?>(nil)
var age = Observable<Double>(0.0)
}
extension SignupViewModel {
var description: String {
return """
username: \(username.value ?? "")
email: \(email.value ?? "")
age: \(age.value)
"""
}
}With the ViewModel configured, we can take a look at SignupViewController. It is quite simple, with a few text fields and a stepper to set the age:
class SignupViewController: UIViewController {
@IBOutlet var ageStepper: UIStepper!
@IBOutlet var ageLabel: UILabel!
@IBOutlet var usernameField: UITextField!
...