Use viewLifecycleOwner as the LifecycleOwner

前端 未结 3 1972
名媛妹妹
名媛妹妹 2021-01-01 09:05

I have a fragment:

class MyFragment : BaseFragment() {

   // my StudentsViewModel instance
   lateinit var viewModel: StudentsViewModel

   override fun onC         


        
3条回答
  •  时光说笑
    2021-01-01 09:24

    Why I get this error?

    Lint is recommending that you use the lifecycle of the fragment's views (viewLifecycleOwner) rather than the lifecycle of the fragment itself (this). Ian Lake and Jeremy Woods of Google go over the difference as part of this Android Developer Summit presentation, and Ibrahim Yilmaz covers the differences in this Medium post In a nutshell:

    • viewLifecycleOwner is tied to when the fragment has (and loses) its UI (onCreateView(), onDestroyView())

    • this is tied to the fragment's overall lifecycle (onCreate(), onDestroy()), which may be substantially longer

    How to get rid of it?

    Replace:

    viewModel.students.observe(this, Observer {
            //TODO: populate recycler view
        })
    

    with:

    viewModel.students.observe(viewLifecycleOwner, Observer {
            //TODO: populate recycler view
        })
    

    In your current code, if onDestroyView() is called, but onDestroy() is not, you will continue observing the LiveData, perhaps crashing when you try populating a non-existent RecyclerView. By using viewLifecycleOwner, you avoid that risk.

提交回复
热议问题