
observable from the Delegates object, which makes a property behave like a regular property but also specifies a function that will be executed whenever the property’s setter is called.var name: String by Delegates.observable("Empty") { prop, old, new -> println("$old -> $new") } fun main() { name = "Martin" // Empty -> Martin name = "Igor" // Martin -> Igor name = "Igor" // Igor -> Igor }
var prop: SomeType by Delegates.observable(initial, operation) // Alternative to var prop: SomeType = initial set(newValue) { field = newValue operation(::prop, field, newValue) }
import kotlin.properties.Delegates.observable val prop: SomeType by observable(initial, operation)
observable delegate if we want to take some action whenever a property value changes, e.g., when we want to log each property change:val status by observable(INITIAL) { _, old, new -> log.info("Status changed from $old to $new") }
observable delegate is often used when a property change should lead to a view update. For instance, when we implement a list adapter (a class that decides how and what elements should be displayed in a list), we should redraw the view whenever the list of elements changes. I often use an observable delegate to do this automatically.var elements by observable(elements) { _, old, new -> if (new != old) notifyDataSetChanged() }
observable delegate to invoke some action when a property changes. We might use it to implement a class that invokes observers whenever an observable property changes.import kotlin.properties.Delegates.observable class ObservableProperty<T>(initial: T) { private var observers: List<(T) -> Unit> = listOf() var value: T by observable(initial) { _, _, new -> observers.forEach { it(new) } } fun addObserver(observer: (T) -> Unit) { observers += observer } } fun main() { val name = ObservableProperty("") name.addObserver { println("Changed to $it") } name.value = "A" // Changed to A name.addObserver { println("Now it is $it") } name.value = "B" // Changed to B // Now it is B }
observable delegate, one property change can influence other properties or our application state. I’ve used this to implement unidirectional data binding when, for instance, I wanted to define a property whose state change influenced changes in a view. This is like the drawerOpen property in the example below, which opens and closes the drawer when set to true or false[^33_2].var drawerOpen by observable(false) { _, _, open -> if (open) drawerLayout.openDrawer(GravityCompat.START) else drawerLayout.closeDrawer(GravityCompat.START) }
var drawerOpen by bindToDrawerOpen(false) { drawerLayout } fun bindToDrawerOpen( initial: Boolean, lazyView: () -> DrawerLayout ) = observable(initial) { _, _, open -> if (open) drawerLayout.openDrawer(GravityCompat.START) else drawerLayout.closeDrawer(GravityCompat.START) }
observable delegate.import kotlin.properties.Delegates.observable var book: String by observable("") { _, _, _ -> page = 0 } var page = 0 fun main() { book = "TheWitcher" repeat(69) { page++ } println(book) // TheWitcher println(page) // 69 book = "Ice" println(book) // Ice println(page) // 0 }
observable delegate to interact with the property value itself. For instance, for one project we decided that a presenter should have sub-presenters, each of which should have its own lifecycle, therefore the onCreate and onDestroy methods should be called when a presenter is added or removed. In order to never forget about these function calls, we can invoke them whenever the list of presenters is changed. After each change, we call onCreate on the new presenters (those that are now but were not before), and we call onDestroy on the removed presenters (those that were before and are not now).var presenters: List<Presenter> by observable(emptyList()) { _, old, new -> (new - old).forEach { it.onCreate() } (old - new).forEach { it.onDestroy() } }
observable delegate can be used. Now, let's talk about this delegate’s brother, which also seems useful but is used much less often in practice.vetoable delegate is very similar to observable, but it can forbid property value changes. That is why the vetoable lambda expression is executed before the property value changes and returns the Boolean type, which determines if the property value should change or not. If this function returns true, the property value will change; if it returns false, the value will not change.var prop: SomeType by Delegates.vetoable(initial, operation) // Alternative to var prop: SomeType = initial set(newValue) { if (operation(::prop, field, newValue)) { field = newValue } }
import kotlin.properties.Delegates.vetoable var smallList: List<String> by vetoable(emptyList()) { _, _, new -> println(new) new.size <= 3 } fun main() { smallList = listOf("A", "B", "C") // [A, B, C] println(smallList) // [A, B, C] smallList = listOf("D", "E", "F", "G") // [D, E, F, G] println(smallList) // [A, B, C] smallList = listOf("H") // [H] println(smallList) // [H] }
vetoable delegate can be used when we have a property with some requirements on its value; whenever someone tries to modify this value, we first need to validate the new value. We might also invoke some actions when a new value is valid (like displaying it) or when it is not (like logging an error). So, this is a conceptual presentation of how vetoable could be used:var name: String by vetoable("") { _, _, new -> if (isValid(new)) { showNewName(new) true } else { showNameError() false } }
vetoable delegate is not used very often, but some practical examples might include allowing only specific state changes in an application, or requiring only valid values.import kotlin.properties.Delegates.vetoable val state by vetoable(Initial) { _, _, newState -> if (newState is Initial) { log.e("Cannot set initial state") return@vetoable false } // ... return@vetoable true } val email by vetoable(email) { _, _, newEmail -> emailRegex.matches(newEmail) }
observable delegate has better synchronization, but this simplified code can help us understand how observable works in general.[^33_2]: I pushed this pattern further in the KotlinAndroidViewBindings library, which makes little sense in modern Android development because it now has good support for
LiveData and StateFlow.[^33_3]: This word is well-known in Poland for historical reasons. You can read about Liberum Veto.
