skip to content

With RecyclerView's ListAdapter, how do DiffUtil.ItemCallback and submitList replace notifyDataSetChanged, and why can an update silently fail to appear?

level: middleimportance: must knowfreq 80%

answer

  1. identity first, then contents
  2. diff off the main thread
  3. updates dispatched as notifyItemRange calls
  4. reference check before diffing
  5. never mutate a submitted list

basics

~20 s

ListAdapter diffs each submitted list against the current one on a background thread using DiffUtil.ItemCallback, then dispatches precise insert, remove, move and change events. Resubmitting the same mutated list instance is ignored, so no update is dispatched.

solid answer

~40 s

`notifyDataSetChanged()` forces a full rebind and relayout of every visible row and gives the animator nothing to animate. `ListAdapter` takes a `DiffUtil.ItemCallback`: `areItemsTheSame` compares identity (an id), `areContentsTheSame` compares what is drawn, and `getChangePayload` can describe a partial change. `submitList` hands the work to an `AsyncListDiffer`, which runs `DiffUtil` on a background executor and dispatches precise `notifyItem*` calls on the main thread. The classic failure: mutating the list you already submitted and calling `submitList` with it again. The differ sees the same reference and returns early without dispatching anything, while the data has already changed underneath RecyclerView. Always submit a new list.

code

kotlin · 22 lines
kotlin
data class Book(val id: Long, val title: String, val downloadProgress: Int)

object BookDiff : DiffUtil.ItemCallback<Book>() {
    override fun areItemsTheSame(oldItem: Book, newItem: Book) = oldItem.id == newItem.id
    override fun areContentsTheSame(oldItem: Book, newItem: Book) = oldItem == newItem
}

class BookAdapter : ListAdapter<Book, BookViewHolder>(BookDiff) {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookViewHolder =
        BookViewHolder(
            LayoutInflater.from(parent.context).inflate(R.layout.item_book, parent, false)
        )

    override fun onBindViewHolder(holder: BookViewHolder, position: Int) {
        holder.bind(getItem(position))
    }
}

// Always a new list: never mutate and resubmit the current one
adapter.submitList(adapter.currentList + newBook) {
    recyclerView.scrollToPosition(adapter.itemCount - 1)
}

go deeper

for a junior

Know that ListAdapter takes a whole new list through submitList and works out the row changes for you, instead of calling notifyDataSetChanged.

for a middle

Explain the three ItemCallback methods and their order, the background diff with a main-thread dispatch, and the same-instance early return in submitList.

for a senior

Diagnose updates that never show or rows that fade on every edit: a mutated list resubmitted, ids compared in areContentsTheSame, whole objects compared in areItemsTheSame.

for a principal

Make immutable list snapshots a team rule at the ViewModel boundary, so every submit is a new list and diffs stay correct.

## The problem ListAdapter solves A plain `RecyclerView.Adapter` has to be told what changed. The blunt way is `notifyDataSetChanged()`. Its javadoc says observers must assume every item and the structure may be invalid, so **LayoutManagers are forced to fully rebind and relayout all visible views**, and the javadoc calls it a last resort. Without stable ids, insert, remove and move animations have nothing to work from, so the list snaps instead of animating. The precise way is the `notifyItemInserted` / `notifyItemRemoved` / `notifyItemMoved` / `notifyItemChanged` family, but computing those calls by hand from two lists is error prone. **`ListAdapter`** does it for you: you hand it a whole new list and it works out the minimal set of updates with **`DiffUtil`**. ## The DiffUtil.ItemCallback contract `ListAdapter<T, VH>` takes a `DiffUtil.ItemCallback<T>` in its constructor. The callback answers three questions about an old item and a new item: | Method | Question it answers | Typical implementation | |---|---|---| | `areItemsTheSame(oldItem, newItem)` | Is this the same entity? | compare a unique id | | `areContentsTheSame(oldItem, newItem)` | Does it look the same on screen? | `oldItem == newItem` on a data class | | `getChangePayload(oldItem, newItem)` | What exactly changed? | optional; returns `null` by default | The order matters. `areContentsTheSame` is called **only** when `areItemsTheSame` returned true, and `getChangePayload` only when items are the same but contents differ. The result becomes `notifyItemRange*` and `notifyItemMoved` calls, dispatched through an `AdapterListUpdateCallback`. Common mistakes with the callback: - **Comparing whole objects in `areItemsTheSame`.** Any edit then looks like a removal plus an insertion: the row fades out and back in, and a row the user was looking at can shift. - **Comparing ids in `areContentsTheSame`.** Every edit is then invisible, so a renamed audiobook keeps its old title on screen. - **Comparing fields that are not shown.** Harmless but wasteful: it triggers rebinds the user cannot see. ## What submitList actually does `ListAdapter` delegates to an `AsyncListDiffer`. Reading its `submitList(newList, commitCallback)` shows four paths: 1. **Same instance as the current list:** returns immediately (it still runs the commit callback). Nothing is diffed. 2. **`null`:** removes everything in one `onRemoved(0, size)` call. 3. **No current list yet:** inserts everything in one `onInserted(0, size)` call, no diff. 4. **Otherwise:** runs `DiffUtil.calculateDiff` on a **background executor**, then hops to the main thread to swap the list in and dispatch the updates. The default background executor is a small fixed pool of two threads, shared by every config that does not set its own through `AsyncDifferConfig.Builder.setBackgroundThreadExecutor`. Each submit increments a generation counter; when a diff finishes after a newer list has been submitted, its result is thrown away. That means the commit callback of a superseded list may never run, which the javadoc warns about. ## The same-instance trap The fast path in step 1 compares references. This is the most common "ListAdapter does not update" bug: ```kotlin books.add(newBook) // mutate the list already submitted adapter.submitList(books) // same instance: returns early, no events dispatched ``` Worse than a missing animation: the adapter reads its items from that same list, so its data changed with no notification. Rows can show stale content until some later layout, and RecyclerView can fail with an `IndexOutOfBoundsException` whose message begins "Inconsistency detected". DiffUtil's own documentation states that `DiffUtil`, `ListAdapter` and `AsyncListDiffer` **require the list not to mutate while in use**, including the item properties used in diffing. Submit a new list every time (`adapter.submitList(adapter.currentList + newBook)` or a fresh list from the ViewModel). `getCurrentList()` hands back an unmodifiable view, and its javadoc says changes must go through `submitList`. ## Reading the update as it lands - `onCurrentListChanged(previousList, currentList)` on `ListAdapter` runs after each commit; for a diffed list that is on the main thread, after the updates are dispatched. - The `commitCallback` overload is the place to scroll to a newly added row, because before it runs the adapter still holds the old list. - `getItem(position)` reads from the current list; never index into a list kept beside the adapter. ## Cost and limits DiffUtil uses Myers's algorithm with an extra pass for moves. Its javadoc gives **O(N + D²)** expected time, where D is the length of the edit script, plus O(MN) for move detection, and a maximum list size of 2^26 items. Because the work runs off the main thread, a library of a few thousand audiobooks diffs without blocking a frame; what remains on the main thread is the dispatch and the rebinds of rows that really changed. ## When notifyDataSetChanged is still used Only when nothing about the change can be described, such as swapping to a completely unrelated data set. Even then, an adapter with stable ids gets some help: RecyclerView tries to synthesise structural change events for it, though every visible row is still rebound. The page-by-page loading adapter is a separate lesson on the Paging library, which reuses the same `DiffUtil.ItemCallback`.

  • On which threads does ListAdapter's diff run and its result land?
    `AsyncListDiffer` runs `DiffUtil.calculateDiff` on the config's background executor, by default a shared fixed pool of two threads, then posts to the main thread to swap the list and dispatch the `notifyItem*` events. The first submission and a `null` submission skip the diff entirely and dispatch one insert or remove at once.
  • After rotation, a RecyclerView fed asynchronously by ListAdapter jumps back to the top. What adapter setting helps?
    `setStateRestorationPolicy(StateRestorationPolicy.PREVENT_WHEN_EMPTY)` on the adapter. By default (`ALLOW`) the saved scroll state is handed to the LayoutManager at the next layout, when the list may still be empty, so it is lost. With `PREVENT_WHEN_EMPTY`, RecyclerView waits until the adapter has at least one item before restoring.
  • Two lists are submitted to a ListAdapter in quick succession. Which commit callbacks run?
    Each submit increments a generation counter, and a diff that finishes after a newer submit is discarded. The newer list's callback runs when it commits; the javadoc warns that the earlier list's callback may never run. Do not rely on every callback firing, only on the last one.

  • notifyDataSetChanged animates inserts and removals as smoothly as ListAdapter does
  • areItemsTheSame should compare every field with equals
  • submitList runs DiffUtil on the main thread before returning
  • Mutating the current list and calling submitList again triggers a fresh diff
  • ListAdapter needs setHasStableIds(true) to animate moves