An example of an observer pattern in Kotlin.
Table of contents for design patterns in Kotlin
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. Wikipedia
Example:
Observer / Listener
interface Observer<TYPE> {
fun onValueChanged(old: TYPE, new: TYPE)
}
Subject
class Subject<TYPE>(initValue: TYPE) {
val observers = mutableListOf<Observer<TYPE>>()
var value: TYPE by Delegates.observable(initValue) { _, old, new ->
observers.forEach { it.onValueChanged(old, new) }
}
}
Usage:
fun main() {
val subject = Subject(0).apply {
observers.add(object : Observer<Int> {
override fun onValueChanged(old: Int, new: Int) {
println("subject onValueChanged(old: $old new: $new)")
}
})
}
subject.value = 1
subject.value = 2
subject.value = 3
}
Result
subject onValueChanged(old: 0 new: 1)
subject onValueChanged(old: 1 new: 2)
subject onValueChanged(old: 2 new: 3)