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
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:
areItemsTheSame
: checks if both objects represent the same item (movie A), returns trueareContentsTheSame
: checks if content is the same (star rating), its not - returns falsegetChangePayload
: called whenareContentsTheSame
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 return4
(stars).
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 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.
© 2022 - 2024 — McMap. All rights reserved.