无法从我的片段中的 ViewModel 观察 LiveData<MutableList<T>>

Ahm*_*hal 3 android mvvm kotlin android-livedata mutablelivedata

我的片段.kt:

viewModel.studentsTemp.observe(this, Observer {
    adapter.submitList(it)
})
Run Code Online (Sandbox Code Playgroud)

MyViewModel.kt

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

仅当应用程序启动时(即创建 ViewModel 时,即当 init 块在 View Model 中运行时)才会调用 Observer。

Fra*_*esc 7

MutableListMutableLiveData. 请注意,如果您添加或删除项目,MutableList这不会触发观察者。要触发观察者,您必须更新LiveData变量。

所以这不会触发观察者

studentsTemp.value?.add(student)
Run Code Online (Sandbox Code Playgroud)

但这会

studentsTemp.value = studentsTemp.value?.add(student) ?: mutableListOf(studen)
Run Code Online (Sandbox Code Playgroud)