9

why need to use areItemsTheSame with areContentsTheSame at diffutil recyclerview? i don't understand i think areItemsTheSame is enough to compare data? is possible more explain to me? thank you

Mehrzad
  • 93
  • 1
  • 6

2 Answers2

10

As short as possible:

areItemsTheSame - used to determine structural changes between old and new list (additions/removals/position changes)

areContentsTheSame - determines if particular item was updated


If objects in your list are immutable you might not have noticed the difference and might as well always return true from areContentsTheSame but it does matter when your items can be updated.

DiffUtil.ItemCallback has 3 methods for a reason. Lets assume you're comparing two objects:

Movie A rated at 5 stars
Movie A rated at 4 stars

When diff is being calculated following calls are made:

  1. areItemsTheSame: checks if both objects represent the same item (movie A), returns true
  2. areContentsTheSame: checks if content is the same (star rating), its not - returns false
  3. getChangePayload: called when areContentsTheSame returns false. It's an optional override that can be used to return payload object for a partial update of a ViewHolder. In this example it can return 4 (stars).
Pawel
  • 15,548
  • 3
  • 36
  • 36
  • thanks for your explanation ,but if my data list doesn't have an id why we need to use 'areItemTheSame' method. assume you're comparing data list like this 'data class(firstname , lastname)' in this example we don't have an id or any unique parameter so how can implement this data list with diffutil? – Mehrzad May 12 '22 at 14:26
  • @Mehrzad `DiffUtil` is used to calculate differences between lists and only dispatch necessary changes to the adapter. If your items do not have ID or other way to fulfill `areItemsTheSame` contract then running `DiffUtil` is pointless as it won't be able to determine additions/removals/movement. – Pawel May 12 '22 at 18:51
2

areItemsTheSame(T, T) is called to see if two objects are the same. If not there may be a need to add/delete the item.

areContentsTheSame is called only when the areItemsTheSame(T, T) return true. In this case, the item was available previously, but the content is changed, so the respective change should be displayed.

getChangePayload (T oldItem, T newItem) is called when areItemsTheSame(T, T) returns true for two items and areContentsTheSame(T, T) returns false for them to get a payload about the change.

Ehsan Mashhadi
  • 2,568
  • 1
  • 19
  • 30