gpt4 book ai didi

android - (可变)LiveData 未在 UI 上观察到

转载 作者:行者123 更新时间:2023-12-04 08:16:23 25 4
gpt4 key购买 nike

我在 SO 上扔了很多类似的帖子,但仍然找不到我无法观察 LiveData 的原因。在用户界面上。
我正在做一个用于学习目的的项目。我想要做的是从我的 Room 中获取一个值数据库并将其显示在 UI 上。为了清楚起见,我只展示了相关的代码 fragment 。
Dao.kt

@Query("SELECT maxValue FROM DoItAgainEntity WHERE id = :id")
fun getMaxValue(id: Int): LiveData<Int>
Repository.kt
override fun getMaxValue(activityId: Int) = doItAgainDao.getMaxValue(activityId)
ViewModel.kt
private val mMaxValue = MutableLiveData<Int>()

override fun getMaxValue(id: Int): LiveData<Int> =
Transformations.switchMap(mMaxValue) {
repository.getMaxValue(id)
}
fragment .kt
viewModel.getMaxValue(activitiesAdapter.activities[position].id)

viewModel.getMaxValue(activitiesAdapter.activities[position].id).observe(viewLifecycleOwner, Observer {
// THIS CODE IS NEVER CALLED
Log.d("getMaxValueObserver",it.toString())
}
我如何联系 Int LiveData 中提供的值目的?我知道,这几乎是一个新手问题,但是你能解释一下我的误解吗?
非常感谢。

最佳答案

您没有更新您的 LiveData,因为您这样做了 switchMapmMaxValue .但是 LiveData 永远不会改变(正如我从您的示例中看到的那样)。
您实际上不需要该属性 private val mMaxValue = MutableLiveData<Int>() .
您可以将函数简化为:

fun getMaxValue(id: Int): LiveData<Int> = repository.getMaxValue(id)
切换映射
  • Documentation

  • Returns a LiveData mapped from the input source LiveData by applying switchMapFunction to each value set on source.

    关于android - (可变)LiveData 未在 UI 上观察到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65684327/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com