【问题标题】:How to observe a reference variable?如何观察参考变量?
【发布时间】:2020-03-23 19:22:24
【问题描述】:

我在下面有一个更新data 变量的类。如何观察此变量何时发生变化?

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 {
}

一些实现接口的类。

class A: Type {}
class B: Type {}

我希望能够在不使用LiveData 或任何Experimental 的情况下观察这些变化。如何让我的代码的其他区域观察data 变量?


我知道有BroadcastChannel,但我不能使用它,因为它是实验性的。

【问题讨论】:

标签: android kotlin coroutine


【解决方案1】:

您可以使用侦听器和内置的 Kotlin 委托:

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()
       }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-23
    • 2012-09-16
    • 1970-01-01
    • 2021-01-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多