0
0
KotlinConceptBeginner · 3 min read

What is Observable Property in Kotlin: Explained with Examples

An observable property in Kotlin is a special kind of property that lets you watch for changes and react whenever its value is updated. You use Delegates.observable to create such properties, which call a callback function every time the property changes.
⚙️

How It Works

Imagine you have a mailbox that not only holds your letters but also rings a bell every time a new letter arrives. An observable property in Kotlin works similarly: it holds a value, but also notifies you whenever that value changes.

Under the hood, Kotlin uses a feature called property delegation to watch the property. When you declare a property as observable, you provide a callback function that runs every time the property’s value is updated. This callback receives the old value and the new value, so you can react accordingly.

This mechanism is useful when you want to track changes without manually checking the value all the time, like updating a user interface or logging changes automatically.

💻

Example

This example shows how to create an observable property that prints a message whenever its value changes.

kotlin
import kotlin.properties.Delegates

class User {
    var name: String by Delegates.observable("Unknown") { prop, old, new ->
        println("Property '${prop.name}' changed from '$old' to '$new'")
    }
}

fun main() {
    val user = User()
    user.name = "Alice"
    user.name = "Bob"
}
Output
Property 'name' changed from 'Unknown' to 'Alice' Property 'name' changed from 'Alice' to 'Bob'
🎯

When to Use

Use observable properties when you want to automatically respond to changes in data without extra code to check for updates. This is common in user interfaces where you want to refresh the screen when data changes, or in logging systems where you want to track changes to important variables.

For example, in an app, you might want to update the display whenever a user's profile information changes. Instead of manually calling update functions everywhere, an observable property can handle this cleanly and efficiently.

Key Points

  • Observable properties notify you on every value change.
  • They use Delegates.observable with a callback function.
  • The callback receives the property, old value, and new value.
  • Useful for UI updates, logging, and reactive programming.

Key Takeaways

Observable properties let you react automatically to value changes.
Use Delegates.observable to create an observable property in Kotlin.
The callback provides old and new values for custom reactions.
Ideal for UI updates, logging, and tracking state changes.