androidlistandroid-recyclerviewcompareandroid-diffutils

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


Solution

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