Reputation: 2418
I have a class below that updates a data
variable. How can I observe when this variable changes?
object Manager {
private var data: Type = B()
fun doWork{
while(active) {
if(conditionA)
data = A()
else if(conditionB)
data = B()
}
}
fun getData(): Flow<Type>
}
interface Type {
}
Some classes that implements the interface.
class A: Type {}
class B: Type {}
I want to be able to observe these changes without using LiveData
or anything that is Experimental
. How can I let other areas of my code observe the data
variable?
I know there is BroadcastChannel
but I cannot use it because it is experimental.
Upvotes: 0
Views: 407
Reputation: 30645
You can use listener and built-in Kotlin delegate:
object Manager {
var dataListeners = ArrayList<(Type) -> Unit>()
// fires off every time value of the property changes
private var data: Type by Delegates.observable(B()) { property, oldValue, newValue ->
dataListeners.forEach {
it(newValue)
}
}
fun doWork{
while(active) {
if(conditionA)
data = A()
else if(conditionB)
data = B()
}
}
}
Upvotes: 1