Sobes.tech
Junior — Middle

How can DiffUtil be used to optimize list updates in RecyclerView?

sobes.tech AI

Answer from AI

DiffUtil is a utility in Android that helps efficiently update lists in RecyclerView by calculating the difference between the old and new list and updating only the changed items.

To apply DiffUtil:

  1. Create a class that inherits from DiffUtil.Callback, where you implement the methods:

    • areItemsTheSame(oldItemPosition, newItemPosition) — checks if two items are the same (e.g., by unique ID).
    • areContentsTheSame(oldItemPosition, newItemPosition) — checks if the contents of the items are the same.
  2. In the RecyclerView adapter, when updating data, create a DiffUtil object and call DiffUtil.calculateDiff().

  3. Pass the result to the adapter via dispatchUpdatesTo() — this will only call the necessary update methods.

Example:

class MyDiffCallback(
    private val oldList: List<Item>,
    private val newList: List<Item>
) : DiffUtil.Callback() {
    override fun getOldListSize() = oldList.size
    override fun getNewListSize() = newList.size

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList[oldItemPosition].id == newList[newItemPosition].id
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        return oldList[oldItemPosition] == newList[newItemPosition]
    }
}

// In the adapter:
fun updateList(newList: List<Item>) {
    val diffResult = DiffUtil.calculateDiff(MyDiffCallback(items, newList))
    items = newList
    diffResult.dispatchUpdatesTo(this)
}

Thus, RecyclerView will only update the changed items, improving performance and interface smoothness.

How can DiffUtil be used to optimize list updates in… - sobes.tech