0

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.

Sergio
  • 27,326
  • 8
  • 128
  • 149
J_Strauton
  • 2,270
  • 3
  • 28
  • 70
  • https://developer.android.com/reference/java/util/Observable or https://developer.android.com/reference/android/databinding/Observable or your own callback system would all seem like possibilities. – CommonsWare Mar 23 '20 at 19:27

1 Answers1

1

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()
       }
    }
}
Sergio
  • 27,326
  • 8
  • 128
  • 149