how to use Architecture Components ViewModel inside RecyclerView Adapter?

前端 未结 3 2009
慢半拍i
慢半拍i 2021-02-02 08:16

I have multiple ViewHolders that work as separated views inside a vertical RecyclerView. I\'m practicing with the new Architecture Components ViewModel.

Inside my ViewMo

3条回答
  •  暖寄归人
    2021-02-02 08:51

    My solution to this issue is;

    • create a new variable(ViewModel) for the layout (fragment or activity layout)
    • in your activity or fragment get the instance of your viewModel with ViewModelProviders
    • hold the data which fills your recyclerView in MutableLiveData and observe it and fill the adapter of recyclerView with the value you observed

    here you mut be careful not to create adapter instance in observe method. if you create it in observe method, it will make leaks

提交回复
热议问题