Junior — Middle
What mechanism within DiffUtil helps update only the changed parts of an item in a list?
sobes.tech AI
Answer from AI
Inside DiffUtil, the method getChangePayload() is used to update only the changed parts of an item. This mechanism allows you to determine which specific fields of an object have changed and pass this data to the adapter to update only the relevant parts of the View, rather than the entire item.
Example of usage:
class MyDiffCallback : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition] == newList[newItemPosition]
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
val oldItem = oldList[oldItemPosition]
val newItem = newList[newItemPosition]
val diffBundle = Bundle()
if (oldItem.title != newItem.title) {
diffBundle.putString("KEY_TITLE", newItem.title)
}
if (oldItem.description != newItem.description) {
diffBundle.putString("KEY_DESCRIPTION", newItem.description)
}
return if (diffBundle.size() == 0) null else diffBundle
}
}
In the adapter, in the onBindViewHolder method, you can handle this payload and update only the changed fields, which improves performance and interface smoothness.