【问题标题】:Android LiveData: Difference between LiveData provided as method or as variableAndroid LiveData:作为方法或变量提供的 LiveData 之间的区别
【发布时间】:2020-05-17 15:12:47
【问题描述】:

在观察作为方法公开的 LiveData 和作为变量公开的 LiveData 之间,我面临着一个奇怪但巨大的行为差异。在您的 ViewModel 中考虑以下代码:

LiveData 作为方法

private val carApiCall = carRepository.getCar(carId)

fun getCarColors() = Transformations.switchMap(carApiCall ) { resource ->
    when (resource.resourceStatus) {
        ResourceStatus.SUCCESS -> databaseRepository.getCarColors(carId)
    }
}

LiveData 作为变量

private val carApiCall = carRepository.getCar(carId)

val carColors = Transformations.switchMap(carApiCall ) { resource ->
    when (resource.resourceStatus) {
        ResourceStatus.SUCCESS -> databaseRepository.getCarColors(carId)
    }
}

如您所见,唯一的区别是 carColors 是如何被外部观察到的。首先作为方法getCarColors(),然后作为公共变量carColors

片段和xml数据绑定布局中的几次观察和使用汽车颜色。

使用可变方法时,一切正常。一旦 API 调用成功,代码就会从数据库中请求汽车颜色一次。

使用方法方式时,API调用执行一次,但其上的Transformation最多调用20次!为什么会这样?

需要说明的是:两个代码示例最终都得到了工作结果,但由于某种原因,第二个示例被执行/调用了很多次,尽管转换后的 apiCall 只更改了一次。

【问题讨论】:

    标签: android android-livedata android-architecture-components android-livedata-transformations


    【解决方案1】:

    当您将其用作方法时,每次尝试访问它时都会单独调用该方法。每次调用getCarColors(),都会执行你写的函数。

    当用作变量时,代码仅在第一次执行 - 这称为变量初始化。一个变量初始化后,它的值会存储在内存中,所以你用来初始化的函数只会被调用一次。

    【讨论】:

    • 是的,我认为它会归结为每当执行数据绑定或其他任何事情时调用的方法。您知道是否有官方建议使用其中一种?因为判断这种行为,我认为将 LiveData 公开为方法(至少在 Kotlin 中)没有任何意义
    • 这真的取决于你想要的行为。有时您希望始终获取新数据,因此方法更有意义。但是如果某些东西是静态的并且不会改变,那么暴露的变量会更好。
    猜你喜欢
    • 2022-01-15
    • 1970-01-01
    • 2020-02-16
    • 2023-04-10
    • 2021-10-08
    • 2019-04-09
    • 1970-01-01
    • 2020-09-18
    • 1970-01-01
    相关资源
    最近更新 更多