August 2017
Intermediate to advanced
440 pages
10h
English
We use the Observer (Listener) pattern when we want to perform operations when an event occurs. In Android development, observers are often set to view elements. Common examples are on-click listeners, on-touch listeners, or text watchers. In Kotlin, we can set listeners with no boilerplate. For example, setting listener on button click looks as follows:
button.setOnClickListener({ someOperation() })
Note that the setOnClickListener is a Java method from the Android library. Later, we will see in detail why we can use it with lambda expressions. The creation of listeners is very simple. Here is an example:
var listeners: List<()->Unit> = emptyList() // 1 fun addListener(listener: ()->Unit) { listeners += listener ...Read now
Unlock full access