Search code examples
android-diffutils

Diffutils: Can add new data but always returns true in areContentsTheSame() when updating an item


in my UI layer

val toMutableList = mAdapter.currentList.toMutableList()
// update data at position 5
val deviceItem = toMutableList[5]
deviceItem.deviceEntity.onLineRefresh = false
mAdapter.submitList(toMutableList)

In my DiffUtil.ItemCallback class

override fun areItemsTheSame(oldItem: DataItem, newItem: DataItem): Boolean {
    TLog.d("DeviceListAdapter", "areItemsTheSame: ")
    return oldItem.deviceId == newItem.deviceId
}

override fun areContentsTheSame(oldItem: DataItem, newItem: DataItem): Boolean {
    return oldItem == newItem
    
}

But adapter not update the Item,and areContentsTheSame always return true,even if I submit a new list.

same Q of Diffutils: Can add new data but always returns true in areItemsTheSame() & areContentsTheSame() when updating an item

Update: I tried many methods,Finally ,find a solution: you need to deep copy the new list


Solution

  • You needs to submit a new list, in order to see a change.

    val toMutableList = mAdapter.currentList.toMutableList()
    mAdapter.submitList(toMutableList)
    

    New List & update old list

    val newList = toMutableList.map { it.copy() }
    newList[5].deviceEntity.onLineRefresh = false
    mAdapter.submitList(newList) {
        toMutableList.clear()
        toMutableList.addAll(newList)
    }