【问题标题】:Android LiveData in Transformation map is null转换映射中的 Android LiveData 为空
【发布时间】:2020-11-17 15:32:12
【问题描述】:

我正面临 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 后,如果我试图获取itemsToDisplay LiveData (itemsToDisplay.value) 的值始终为空

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 计算,是否有人知道它是否不包含该值,或者它可能是一个潜在的错误?

【问题讨论】:

    标签: android kotlin android-livedata android-livedata-transformations


    【解决方案1】:

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

    【讨论】:

    • 首先,非常感谢您的回复!我不知道...但是我有一个疑问,如果我将其更改为var,您将如何声明初始化或设置器以保持 LiveData 值?
    • @Alejandro 为什么你需要var 和setter,如果你需要保持LiveData 值?
    • 嗯,如果我理解支持字段,我需要将其更改为 var,否则它不会像现在一样保留 LiveData 值
    • @Alejandro 使用我回答中的代码,它将创建支持字段
    • 非常感谢!有效!对不起,我没有正确阅读您的答案,明白了。再次感谢您花时间解释它!
    猜你喜欢
    • 1970-01-01
    • 2023-04-10
    • 2013-05-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多