Reputation: 2288
I have a "simple" example of the recommended framework for Android/Room/LiveData.
I get the LiveData update successfully via the Observer in the activity.
The data comes back in the form of a List<Reader>
. Each 'Reader' has a unique field called String token
.
The observer then takes the List<Reader>
and adds it to a new Adapter
which is then applied to the RecyclerView.
So...this causes the issue of the RecyclerView updating and causing a large UI change (scroll back to top for example). I may have background processes that cause some changes of the model and don't want a full re-draw of the RecyclerView...but just the applicable views to be updated with the new LiveData.
How can I then go about updating the RecyclerView without causing the recycler to "re-draw". I.e. I don't want to create a new Adapter();
and apply it to the RecyclerView...but rather just update the Data already in the adapter and change some of the fields in the views in the recycler without effecting the user's experience.
Thanks!
Upvotes: 4
Views: 1939
Reputation: 1037
The tool to help you here is the the DiffUtil. DiffUtil takes the new data and compares it with what the recyclerview already has. It then updates only the specific items which have changed or moved.
With diffutil, you need to implement 2 methods which tell the recyclerview whether the data has changed or not:
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {
return mOldEmployeeList.get(oldItemPosition).getId() == mNewEmployeeList.get(
newItemPosition).getId();
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {
final Employee oldEmployee = mOldEmployeeList.get(oldItemPosition);
final Employee newEmployee = mNewEmployeeList.get(newItemPosition);
return oldEmployee.getName().equals(newEmployee.getName());
}
You can refer to it here: https://developer.android.com/reference/android/support/v7/util/DiffUtil
Upvotes: 1