Problems with DiffUtil. It works slowly and sometimes incorrectly

959 Views Asked by At

I started learning DiffIUtil and met some problems. I want to write a simple android app with a seachview and a recyclerview what use DiffUtil, but the recycler sometimes shows uncorrect data despite right data coming to the recycler.

Here is my data class:

    var id: Int = 0,
    var name: String,
    var lastname: String,
    var number: String,
    val picId: Int
) 

My DiffUtilCallback

class ContactDiffUtilCallBack(
    private val oldList: List<ContactData>,
    private val newList: List<ContactData>
) : DiffUtil.Callback() {
    override fun getOldListSize(): Int = oldList.size

    override fun getNewListSize(): Int = newList.size

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        val oldItem = oldList[oldItemPosition]
        val newItem = newList[newItemPosition]

        return ((oldItem.id) == (newItem.id))
    }

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
        val oldItem = oldList[oldItemPosition]
        val newItem = newList[newItemPosition]

        return (oldItem.number).equals(newItem.number)
                && (oldItem.name).equals(newItem.name)
                && (oldItem.lastname).equals(newItem.lastname)
                && (oldItem.picId).equals(newItem.picId)
    }
}

and this is the function I use to update data in recycler

fun changeContacts(list: List<ContactData>) {
            val oldContacts = getContactList()
            val diffUtilCallback = ContactDiffUtilCallBack(oldList = oldContacts, newList = list)
            val result = DiffUtil.calculateDiff(diffUtilCallback, false)
            contacts = list
            result.dispatchUpdatesTo(this)
        }

Can you give me the cue what i am doing wrong?

1

There are 1 best solutions below

0
On

You're likely better off using DiffUtil.ItemCallback, which compares two items with each other:

class ContactDiffUtilItemCallback : DiffUtil.ItemCallback<ContactData>() {
    override fun areItemsTheSame(oldItem: ContactData, newItem: ContactData): Boolean =
        oldItem.id == newItem.id

    override fun areContentsTheSame(oldItem: ContactData, newItem: ContactData): Boolean =
        oldItem == newItem

}

You can then send an instance of ContactDiffUtilItemCallback into your Adapter class (probably want a `ListAdapter) and it'll automatically calculate things for you.