我有一个片段:
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) {
...
}
}
Back to MyFragment
, in function updateStudentList()
I get compiler error complaining the this
parameter I passed in to .observe(this, Observer{...})
that Use viewLifecycleOwner as the LifecycleOwner
为什么我会收到此错误?如何摆脱它?
原文由 user842225 发布,翻译遵循 CC BY-SA 4.0 许可协议
Lint 建议您使用片段视图的生命周期 (
viewLifecycleOwner
) 而不是片段本身的生命周期 (this
)。 Google 的 Ian Lake 和 Jeremy Woods 在 本次 Android 开发者峰会演示 中讨论了差异,而 Ibrahim Yilmaz 在 这篇 Medium 帖子中 介绍了差异 简而言之:viewLifecycleOwner
绑定到片段具有(和丢失)其 UI 时(onCreateView()
,onDestroyView()
)this
与片段的整个生命周期相关(onCreate()
,onDestroy()
),可能会更长代替:
和:
在您当前的代码中,如果
onDestroyView()
被调用,但是onDestroy()
没有被调用,您将继续观察LiveData
,当您尝试弹出一个不存在的崩溃时,bu0-RecyclerView
。通过使用viewLifecycleOwner
,您可以避免这种风险。