我面临着 Android LiveData 和 Transformation map 的问题。我来解释一下这个案例:
我有一个 SingleLiveEvent 和 LiveData,如下所示(一个用于所有项目,另一个用于在屏幕上显示的项目):
val documents: SingleLiveEvent<List<DocumentData>> = SingleLiveEvent()
val itemsToDisplay: LiveData<List<DocumentData>>
get() {
return Transformations.map(documents) { documents ->
return@map documents.filter { showOptionals || it.isMandatory }
}
}
在 Fragment 中,观察 itemsToDisplay
后,如果我尝试获取 itemsToDisplay
LiveData (itemsToDisplay.value
) 的值始终为 null
itemsToDisplay.observe(this, Observer {
// Inside this method I need to get a calculated property from VM which uses
```itemsToDisplay.value``` and I would like to reuse across the app
loadData(it)
})
// View Model
val hasDocWithSign: Boolean
get() {
return **itemsToDisplay.value**?.any { it.isSignable } ?: false
}
有谁知道 LiveData 是否不保存使用 Transformation.map
计算的值,或者它可能是一个潜在的错误?
最佳答案
当您调用 itemsToDisplay
时,您会得到一个新的空 LiveData 实例,因为您将其声明为没有支持字段的 getter。
val itemsToDisplay: LiveData<List<DocumentData>>
= Transformations.map(documents) { documents ->
documents.filter { showOptionals || it.isMandatory }
}
https://kotlinlang.org/docs/reference/properties.html#backing-fields
关于转换映射中的 Android LiveData 为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64878282/