DiffUtil is a utility class that can calculate the difference between two lists and output a list of operations that converts the first list into the second one.
Diffutil is an alternative for notifyDataSetChanged() in RecyclerView Adapter.
Calling notifyDataSetChanged() on the adapter is expensive because it refreshes all the rows in the list by recreating the entire viewHolders used in that list.
The Diffutil API update only rows those contents that need to be updated, hence it helps us to save memory and improve performance.
CallBack Methods of DiffUtil API:
getOldListSize(): This method returns the size of old list.
getNewListSize(): This method returns the size of new list.
areItemsTheSame(int oldItemPosition, int newItemPosition) : This method compares each item in the old list and the new list for checking whether individual items are the same or not. The comparison is done using ids of each item. If individual items are the same, then this method returns true, otherwise, it returns false.
areContentsTheSame(int oldItemPosition, int newItemPosition): This method checks whether contents(data in each item) of the old list and new list are the same or not. This method is called by diffutil only if areItemsTheSame method returns true.
getChangePayload(int oldItemPosition,int newItemPosition): This method is called by the DiffUtil API only if areItemsTheSame returns true and areContentsTheSame returns false. This method returns an object that contains the data change payload. From this method, we can detect the change in data and pass the changed data to the recycler adapter in the form of a bundle object.
In this video, we create an android app that demonstrates how to update RecyclerView content using DiffUtil API.
Like my Facebook page: / codeglympse
Subscribe My YouTube channel: / ticoontechnologies