androidkotlinmvvmviewmodelandroid-adapter

MVVM- check updates with Recyclerview adapter


I am having hard times understanding updating my recyclerView- Adapter items with a Live-Data<List<SomeObject>>.

Let's say I have a RecyclerViewAdapter in my Fragment which I initialize with an empty list inside. When my Live-Data is loaded successfully, the observer of the LiveData will be activated and a function updateAdapter gets called of My RecyclerViewAdapter.

My Question is: I programmed it so that the adapter checks the recent list of objects in the adapter with the live data object

-> if there are more objects in the liveData (than in the variable of the RecyclerViewAdapter)-> add the objects in this list and notify

-> if there are less objects in the liveData (than in the variable of the RecyclerViewAdapter) -> remove the objects in this list and notify

This works fine for me. But what if I only modify an object e.x his name which will be displayed in the item-container. Should I check every Object attribute in the adapter for every Object ?

Is my approach right ?


Solution

  • This is a best use case of ListDiffer in Android RecyclerView. ListDiffer will iterate your list and will notify the changes done in the data list. Since they are provided by the Android itself, you don't have to maintain a large chunk of code by yourself.

    Check the expample given in the Doc https://developer.android.com/reference/androidx/recyclerview/widget/AsyncListDiffer .