[英]How can we combine SavedStateHandler with LiveData Coroutine Builder?
In a typical Android ViewModel, we can easily create a Restorable LiveData using在典型的 Android ViewModel 中,我们可以使用
val liveData = savedStateHandle.getLiveData<String>("SomeKey")
Whenever the liveData value is set, it is automatically saved and restorable每当设置 liveData 值时,它会自动保存和恢复
However, if we use the liveData
coroutine builder (ie https://developer.android.com/topic/libraries/architecture/coroutines#livedata )但是,如果我们使用
liveData
协程构建器(即https://developer.android.com/topic/libraries/architecture/coroutines#livedata )
val liveDataSaved: LiveData<String> = liveData {
emit(someValue)
}
How can we also join it with savedStateHandle
?我们如何也加入到
savedStateHandle
? (eg when restoring, it will first retrieved the previous emitted value instead of reinitialize) (例如恢复时,它会首先检索之前发出的值,而不是重新初始化)
Note: I can do as below, just look hacky.注意:我可以做如下,只是看起来很hacky。
val liveDataSaved: LiveData<String> = liveData {
val someValue = savedStateHandle.get("Key") ?: getValue()
savedStateHandle.put("Key", someValue)
emit(someValue)
}
You can use MediatorLiveData to combine multiple other live data sources and then observe on this resulting MediatorLiveData
at the end.您可以使用MediatorLiveData组合多个其他实时数据源,然后在最后观察这个生成的
MediatorLiveData
。
In your case, you can have multiple sources to this MediatorLiveData
something like below:在您的情况下,您可以有多个来源到此
MediatorLiveData
,如下所示:
val liveDataValue = MediatorLiveData<String>().apply {
var intermediateValue = ""
fun update() {
this.value = intermediateValue
}
addSource(savedStateHandle.getLiveData<String>("SomeKey")) {
intermediateValue = it
update()
}
addSource(
liveData {
emit(someValue)
}
) {
intermediateValue = it
update()
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.