why use areItemsTheSame with areContentsTheSame at diffutil recyclerview?
Asked Answered
M

2

11

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

Mika answered 9/5, 2022 at 20:42 Comment(0)
T
18

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).
Taboo answered 9/5, 2022 at 21:39 Comment(2)
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?Mika
@Mika 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.Taboo
D
3

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.

Dietetics answered 6/7, 2022 at 18:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.