How to set up a listener for a variable in Kotlin
You can use built-in Kotlin delegates, for example:
object SignalChange {
var refreshListListeners = ArrayList<InterfaceRefreshList>()
// fires off every time value of the property changes
var property1: String by Delegates.observable("initial value") { property, oldValue, newValue ->
// do your stuff here
refreshListListeners.forEach {
it.refreshListRequest()
}
}
}
interface InterfaceRefreshList {
fun refreshListRequest()
}
Add listeners like this:
SignalChange.refreshListListeners.add(object : InterfaceRefreshList {
override fun refreshListRequest() {
refreshList()
}
})
OR
Intead of interface you can use lambda:
object SignalChange {
var refreshListListeners = ArrayList<() -> Unit>()
// fires off every time value of the property changes
var property1: String by Delegates.observable("initial value") { property, oldValue, newValue ->
// do your stuff here
refreshListListeners.forEach {
it()
}
}
}
And to add listener just call:
SignalChange.refreshListListeners.add(::refreshList)
//or
SignalChange.refreshListListeners.add { refreshList() }
fun refreshList() {
}
The simple way to Listen to variable in KOTLIN
private var myVariableName by Delegates.observable(0) { property, oldValue, newValue ->
Log.d(TAG,"New Value $newValue")
Log.d(TAG,"Old Value $oldValue")
}
for more info read https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.properties/-delegates/