Observer

The Observer pattern allows an object to determine the state change of another object. An instance that is interested can subscribe and immediately be notified when the value of a certain field is changed. The following diagram shows this case:

The preceding diagram contains the TextChangeListener interface, which is implemented by the Observer class. The TextInput class contains a reference of the TextChangeListener type. Whenever the text property of an instance of the TextInput class is changed, the onTextChange method is invoked.

The following snippet demonstrates how this pattern can be implemented:

typealias TextChangeListener = (text: String?) -> Unit

class TextInput {
var text: String? = null
set(value) {
field = value
textChangeListener?.invoke(value)
}
var textChangeListener: TextChangeListener? = null
}

We can observe changes in the text property in the following way:

fun main(args: Array<String>) {
val textInput = TextInput().apply {
this.textChangeListener = {println(it)}
}
textInput.text = "Typing"
}

The output of this is as follows:

Typing

It's worth mentioning that we can also use a delegate from the Kotlin standard library:

class TextInput {
var text by Delegates.observable<String?>(null) { _, _, newValue ->
textChangeListener?.invoke(newValue)
}
var textChangeListener: TextChangeListener? = null
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.130.199