我有一个片段:
class MyFragment : BaseFragment() {
// my StudentsViewModel instance
lateinit var viewModel: StudentsViewModel
override fun onCreateView(...){
...
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProviders.of(this).get(StudentsViewModel::class.java)
updateStudentList()
}
fun updateStudentList() {
// Compiler error on 'this': Use viewLifecycleOwner as the LifecycleOwner
viewModel.students.observe(this, Observer {
//TODO: populate recycler view
})
}
}
在我的片段中,我有一个StudentsViewModel实例,该实例在中启动onViewCreated(...)
。
在中StudentsViewModel
,students
是LiveData
:
class StudentsViewModel : ViewModel() {
val students = liveData(Dispatchers.IO) {
...
}
}
返回MyFragment
,在功能上updateStudentList()
,我得到编译器错误抱怨this
我中传递的参数.observe(this, Observer{...})
是Use viewLifecycleOwner as the LifecycleOwner
为什么会出现此错误?如何摆脱它?
IllegalStateException: Can't access the Fragment View's LifecycleOwner when getView() is null i.e., before onCreateView() or after onDestroyView()