Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Trigger updates via. property observer
// embed in the target (note props are read only)
protocol MySensor {
var name: String { get }
var age: Int { get }
}
// an example target that holds sensor
protocol MyView {
var sensor: MySensor { get set }
}
// dispatcher implements sensor
class Dispatcher: MySensor {
var name: String = "John"
var age: Int = 20
}
class ConcreteView: MyView {
var sensor: MySensor {
didSet {
// this gets triggered when presenter updates
render(name: sensor.name, age: sensor.age)
}
}
init(sensor: MySensor) {
self.sensor = sensor
}
func render(name: String, age: Int) {
print("name: \(name), age: \(age)")
}
}
class Presenter {
var view: MyView
// source holds dispatcher with read write acess
var dispatcher: Dispatcher
init() {
self.dispatcher = Dispatcher()
self.view = ConcreteView(sensor: dispatcher)
}
func updateState(name: String, age: Int) {
// update state
dispatcher.name = name
dispatcher.age = age
// trigger update by reseting the sensor
view.sensor = dispatcher
}
}
var presenter = Presenter()
// we update the state triggering the sensor in the view to render
presenter.updateState(name: "Bob", age: 30) // name: Bob, age: 30
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.