转换映射中的 Android LiveData 为 null

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

我面临着 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/

相关文章:

android - Activity 创建了两次

Android通知栏点击不起作用

android - Firebase Firestore Kotlin API 将数据导入自定义对象时出错 : None of the following functions can be called with the arguments supplied

scala - Kotlin(和 Scala): No parameter with index 0-0 (name=reverser$module$1 access=16) in method scala. collection.TraversableOnce.reverser$2

android -room - 在房间数据库中保存对象

java - Android 中的傅里叶逆变换

android - 如何获取手机序列号 (IMEI)

android - RxJava 调用每个列表项

android - Rxjava 返回 LiveData 列表

android - 在 onActivityCreated 或 onViewCreated 中观察 LiveData 是否安全