Recycler View: DiffUtil

  • getOldListSize()– Return the size of the old list.
  • getNewListSize()– Return the size of the new list.
  • areItemsTheSame(int oldItemPosition, int newItemPosition)– It decides whether two objects are representing same items or not.
  • areContentsTheSame(int oldItemPosition, int newItemPosition)– It decides whether two items have same data or not. This method is called by DiffUtil only if areItemsTheSame() returns true.
  • getChangePayload(int oldItemPosition, int newItemPosition)– If areItemTheSame() returns true and areContentsTheSame() returns false then DiffUtil utility calls this method to get a payload about the change.

Getting Started

Below are a simple Student class which is using in the StudentRecyclerViewAdapter and StudentDiffCallback to sort the students list.

public class Student {
public int id;
public String name;
public String class;
}
public class StudentDiffCallback extends DiffUtil.Callback { private final List<Student> mOldStudentList; 
private final List<Student> mNewStudentList;

public StudentDiffCallback(List<Student> oldStudentList, List<Student> newStudentList) {
this.mOldStudentList = oldStudentList;
this.mNewStudentList = newStudentList;
}
@Override
public int getOldListSize() {

return mOldStudentList.size();
}
@Override
public int getNewListSize() {

return mNewStudentList.size();
}
@Override
public boolean areItemsTheSame(int oldItemPosition, int newItemPosition) {

return mOldStudentList.get(oldItemPosition).getId() == mNewStudentList.get(newItemPosition).getId();
}
@Override
public boolean areContentsTheSame(int oldItemPosition, int newItemPosition) {

final Student oldStudentData = mOldStudentList.get(oldItemPosition);
final Student newStudentData = mNewStudentList.get(newItemPosition);
return oldStudentData.getName().equals(newStudentData.getName());
}
@Nullable @Override
public Object getChangePayload(int oldItemPosition, int newItemPosition)
{
return super.getChangePayload(oldItemPosition, newItemPosition);
}
}
public void updateList(ArrayList<Student> newList) {   DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff(new StudentDiffCallback(this.mStudentList, newList));  
this.mStudentList.clear();
this.mStudentList.addAll(newList); diffResult.dispatchUpdatesTo(this);
}

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store