0Pricing
Android Academy · Lesson

Adapters & DiffUtil

Build efficient, animated list adapters with ListAdapter and DiffUtil.ItemCallback. Use submitList() for smooth, partial updates.

The Problem with notifyDataSetChanged()

When your RecyclerView data changes, calling notifyDataSetChanged() redraws every item — even unchanged ones. This causes:

  • No item animations
  • Poor performance on large lists
  • Flickering UI

DiffUtil calculates the minimum set of changes and applies them with smooth animations.

DiffUtil.ItemCallback

Define how two items are compared. Two questions to answer:

  • areItemsTheSame — do they represent the same logical item? (usually compare IDs)
  • areContentsTheSame — are all the visible fields identical?
data class Post(val id: Int, val title: String, val likes: Int)

class PostDiffCallback : DiffUtil.ItemCallback<Post>() {

    override fun areItemsTheSame(oldItem: Post, newItem: Post): Boolean {
        return oldItem.id == newItem.id   // same post?
    }

    override fun areContentsTheSame(oldItem: Post, newItem: Post): Boolean {
        return oldItem == newItem         // data class equality (all fields)
    }
}

All lessons in this course

  1. Kotlin Collections
  2. RecyclerView Basics
  3. RecyclerView Click Events
  4. SharedPreferences
  5. DataStore Preferences
  6. Adapters & DiffUtil
← Back to Android Academy