Sobes.tech
Junior — Middle

Որ մեխանիզմը DiffUtil-ի ներսում օգնում է թարմացնել միայն փոփոխված մասերը ցանկում?

sobes.tech AI

Պատասխան AI-ից

DiffUtil-ի ներսում, միայն փոփոխված տարրերի մասերը թարմացնելու համար օգտագործվում է getChangePayload() մեթոդը: Այս մեխանիզմը թույլ է տալիս ճշգրիտ որոշել, թե որ օբյեկտի դաշտերն են փոխվել, և փոխանցել այդ տվյալները ադապտերին, որպեսզի թարմացնի միայն համապատասխան View մասերը, ոչ թե ամբողջ տարրը:

Օգտագործման օրինակ:

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
    }
}

Ադապտերում, onBindViewHolder մեթոդում, կարելի է մշակել այս payload-ը և թարմացնել միայն փոփոխված դաշտերը, ինչը բարելավում է կատարողականությունը և հոսունությունը։