Using DiffUtil in Android RecyclerView
DiffUtil is a utility class that can calculate the difference between two lists and output a list of update operations that converts the first list into the second one.It can be used to calculate updates for a RecyclerView Adapter.
Most of the time our list changes completely and we set new list to RecyclerView Adapter. And we call notifyDataSetChanged to update adapter. NotifyDataSetChanged is costly. DiffUtil class solves that problem now. It does its job perfectly!
Lets create a usecase for that. Lets say we have a person list which we add persons randomly. Then we sort the list by age and update recyclerview.
I am going to use static data to keep implementation simple.
Here is our player comes to the ring. DiffUtil.Callback is an abstract class and it has 4 abstract methods and 1 method non-abstract method. Let explain them shortly.
getOldListSize() : It returns the size of the old list.
getNewListSize() : Returns the size of the new list;
areItemsTheSame(int oldItemPosition, int newItemPosition) : Called by the DiffUtil to decide whether two object represent the same Item.If your items have unique ids, this method should check their id equality.
areContentsTheSame(int oldItemPosition, int newItemPosition) : Checks whether two items have the same data.You can change its behavior depending on your UI. This method is called by DiffUtil only if areItemsTheSame returns true.
getChangePayload(int oldItemPosition, int newItemPosition) : If areItemTheSame return true and areContentsTheSame returns false DiffUtil calls this method to get a payload about the change. For my example I didn’t use payload object but if you want to use it you can go through this example.
Update method in my RecyclerViewAdapter
That’s all. We call dispactUpdatesTo(RecyclerView.Adapter) method and adapter will be notified about the change.