gpt4 book ai didi

delegates - Kotlin 委托(delegate)更有趣

转载 作者:行者123 更新时间:2023-12-03 08:22:38 24 4
gpt4 key购买 nike

如果您知道 Google 的实验性 Android 架构组件,您可能知道 MutableLiveData .为了让它更有趣,我提供了:

class KotlinLiveData<T>(val default: T) {
val data = MutableLiveData<T>()

operator fun getValue(thisRef: Any?, property: KProperty<*>):T {
return data.value ?: default
}

operator fun setValue(thisRef: Any?, property: KProperty<*>, value:T) {
if (Looper.myLooper() == Looper.getMainLooper()) {
data.value = value
} else {
data.postValue(value)
}
}
}

然后我可以:
var name : String by KotlinLiveData("not given")
name = "Chrzęszczybrzęczykiewicz"

但是,唉 - 这使得 data这是需要的,即注册 Observer无法访问:
name.data.observe(this, nameObserver) // won't work :(

知道我是否能以某种方式得到它?

最佳答案

感谢热键的解决方案,这里有一些更好的代码:

class KotlinLiveData<T>(val default: T, val liveData : MutableLiveData<T>? = null) {
val data = liveData ?: MutableLiveData<T>()

operator fun getValue(thisRef: Any?, property: KProperty<*>):T {
return data.value ?: default
}

operator fun setValue(thisRef: Any?, property: KProperty<*>, value:T) {
if (Looper.myLooper() == Looper.getMainLooper()) {
data.value = value
} else {
data.postValue(value)
}
}
}

inline fun <reified R> KMutableProperty0<*>.getLiveData(): MutableLiveData<R> {
isAccessible = true
return (getDelegate() as KotlinLiveData<R>).data
}

inline fun <reified R> KMutableProperty0<*>.observe(owner: LifecycleOwner, obs : Observer<R>) {
isAccessible = true
(getDelegate() as KotlinLiveData<R>).data.observe(owner,obs)
}

现在我能:
someViewModel::name.observe(myActivity, Observer<String>{...})

someViewModel.name = "Kowalski, Leon"
按预期工作

此类允许使用 LiveData 和 Android 数据绑定(bind)开箱即用。

关于delegates - Kotlin 委托(delegate)更有趣,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844933/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com