NOTE:
Before reading, you should know about 'Delegate Properties' in Kotlin.
For more information, please find:
http://kotlinlang.org/docs/reference/delegated-properties.html
Observer
The observer pattern is used to allow an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.
Setup:
- Observer
- Subject
- Client
Observer Example:
import kotlin.properties.Delegates
// Step 4: Client code
fun main(args: Array<String>) {
val chemeleon = Chemeleon()
chemeleon.observer = LogChemeleonColorObserver()
chemeleon.color = "RED"
chemeleon.color = "GREEN"
chemeleon.color = "GREY"
}
// Step 1: Create an observer interface
interface ChemeleonColorObserver{
fun onColorChange(newColor: String)
}
// Step 2: Implement concrete observer class
class LogChemeleonColorObserver: ChemeleonColorObserver{
override fun onColorChange(newColor: String) {
println("Look, the chemeleon changes to $newColor")
}
}
// Step 3: Create subject class
class Chemeleon {
var observer: ChemeleonColorObserver? = null
var color: String by Delegates.observable(""){
property, oldValue, newValue -> observer?.onColorChange(newValue)
}
}
/*
Prints:
Look, the chemeleon changes to RED
Look, the chemeleon changes to GREEN
Look, the chemeleon changes to GREY
*/
Listener Example
import kotlin.properties.Delegates
// Step 4: Client usage example
fun main(args: Array<String>){
val textView = TextView()
textView.listener = PrintingTextChangedListener()
textView.text = "Kotlin"
textView.text = "java"
}
// Step 1: Create a listener interface
interface TextChangedListener {
fun onTextChanged(newText: String)
}
// Step 2: Implement a listener class
class PrintingTextChangedListener: TextChangedListener{
override fun onTextChanged(newText: String) {
println("The text has been changed to $newText")
}
}
// Step 3: Create an subject class
class TextView {
var listener: TextChangedListener? = null
var text: String by Delegates.observable(""){
_, _, new -> listener?.onTextChanged(new)
}
}
/*
prints
The text has been changed to Kotlin
The text has been changed to java
*/
<END>