【问题标题】:Cannot observe LiveData<MutableList<T>> from ViewModel in my fragment在我的片段中无法从 ViewModel 观察 LiveData<MutableList<T>>
【发布时间】:2020-04-07 18:38:13
【问题描述】:

MyFragment.kt:

viewModel.studentsTemp.observe(this, Observer {
    adapter.submitList(it)
})

MyViewModel.kt

private var _studentsTemp = MutableLiveData<MutableList<Student>>()
val studentsTemp: LiveData<MutableList<Student>> get() = _studentsTemp
init {
        _studentsTemp.value = mutableListOf<Student>()
}

仅在应用程序启动时调用观察者,即创建 ViewModel 时,即在 View Model 中运行 init 块时。

【问题讨论】:

  • 对于所有其他案例观察员都在工作。除了这种情况。
  • 在片段中你应该使用viewLifecycleOwner而不是this
  • @IR42 好的,谢谢。您能否还解释一下为什么我们在使用 ViewModels 时在 Fragments 中使用binding.lifecycleowner = this?我是新手。

标签: android kotlin mvvm android-livedata mutablelivedata


【解决方案1】:

您的MutableLiveData 中有一个MutableList。请注意,如果您从 MutableList 添加或删除项目,这不会触发观察者。要触发观察者,您必须更新 LiveData 变量。

所以这不会触发观察者

studentsTemp.value?.add(student)

但这会

studentsTemp.value = studentsTemp.value?.add(student) ?: mutableListOf(studen)

【讨论】:

  • 非常感谢您引起我的注意。我刚刚在 add 函数之后添加了 _studentsTemp.value = _studentsTemp.value 行,它触发了观察者。
猜你喜欢
  • 2020-03-17
  • 1970-01-01
  • 2018-05-10
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多