-
Notifications
You must be signed in to change notification settings - Fork 23
Delegation : By using Observable
Devrath edited this page Feb 28, 2024
·
3 revisions
Observation
- Notice in the output every time we modify the variable, It gives the
oldValue
andnewValue
. - We can do something in the block when the value is accessed or modified.
- If we just access the variable, it will just return the value, and the block is not executed.
- Note we cannot reassign the variable inside the block.
Code
class MainActivity : ComponentActivity()
{
private var demoObject by Delegates.observable(initialValue = 5) { property, oldValue, newValue ->
println("OldValue:---> $oldValue")
println("NewValue:---> $newValue")
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
demoObject = 8
demoObject = 15
setContent {}
}
}
Output
OldValue:---> 5
NewValue:---> 8
OldValue:---> 8
NewValue:---> 15