Skip to content

Instantly share code, notes, and snippets.

@sebastienwindal
Created January 17, 2019 15:55
Show Gist options
  • Save sebastienwindal/43759257f1f74840a9a2509cc70e1eca to your computer and use it in GitHub Desktop.
Save sebastienwindal/43759257f1f74840a9a2509cc70e1eca to your computer and use it in GitHub Desktop.
Simple reactive MVVM with KVO
import UIKit
//
// ViewModel, all KVO compliant to ViewController can observe changes in a decouple way.
//
class MyViewModel: NSObject {
@objc dynamic var firstName:String = ""
@objc dynamic var lastName: String = ""
// Fullname, concatenation of first and last.
@objc dynamic var fullName:String {
return "\(firstName) \(lastName)"
}
@objc private static let keyPathsForValuesAffectingFullName: Set<String> = [#keyPath(firstName), #keyPath(lastName)]
}
class MyController {
let viewModel = MyViewModel()
// KVO observer blocks need to be stronly retained somewhere.
// this array serves this porpose.
var observers = [NSKeyValueObservation]()
init() {
let nameObserver = viewModel.observe(\.firstName, options: [.initial, .new]) { (model, change) in
print("nameObserver kicked in: \(change.newValue)")
}
let fullNameObserver = viewModel.observe(\.fullName, options: [.initial, .new]) { (model, change) in
print("fullnameObserver kicked in \(change.newValue) \(self.viewModel.fullName)")
print("s")
}
observers.append(nameObserver)
observers.append(fullNameObserver)
}
func doStuff() {
viewModel.firstName = "Sebastien"
viewModel.lastName = "Windal"
}
}
let myController = MyController()
myController.doStuff()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment