2

我正面临 Android LiveData 和转换地图的问题。我将解释这个案例:

我有一个 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,如果我试图获取itemsToDisplayLiveData( 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或者它可能是一个潜在的错误?

4

1 回答 1

2

当您调用时,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

于 2020-11-17T16:39:51.127 回答