Mehrzad
Mehrzad

Reputation: 123

why use areItemsTheSame with areContentsTheSame at diffutil recyclerview?

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

Upvotes: 11

Views: 6368

Answers (2)

EMEM
EMEM

Reputation: 3148

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.

Upvotes: 3

Pawel
Pawel

Reputation: 17288

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).

Upvotes: 18

Related Questions