使用 diffUtils 更新列表的最佳方式是什么

what is the best way to update a list with diffUtils

我想用 diffUtils 更新列表项,但在我用 diffDiffUtils 设置列表后,如下所示:

val coinsDiffUtil = DataDiffUtilCallBack(itemList, newData)
val diffUtilResult = DiffUtil.calculateDiff(coinsDiffUtil)
itemList = ArrayList(newData)
diffUtilResult.dispatchUpdatesTo(this)

diff util 不更新 recyclerView 项目所以我使用这样的函数:

fun updateItem(item: Model) {
    val index = itemList.indexOfFirst {
        it.id == item.id
    }
   itemList[index].enabled = item.enabled
   notifyItemChanged(index)
}

最简单的方法是使用 ListAdapter 并将您的 DiffUtil.ItemCallback 传递给它 ref , 例子

class RecyclerViewTodoAdapter : ListAdapter<Task, RecyclerViewTodoAdapter.LayoutViewHolder>(
    DIFF_CALLBACK
) {

    companion object {
        val DIFF_CALLBACK: DiffUtil.ItemCallback<Task> = object : DiffUtil.ItemCallback<Task>() {
            override fun areItemsTheSame(oldItem: Task, newItem: Task): Boolean {
                return oldItem.equals(newItem)
            }

            override fun areContentsTheSame(oldItem: Task, newItem: Task): Boolean {
                // check for contents
                return oldItem.taskName == newItem.taskName &&
                        oldItem.summary == newItem.summary &&
                        oldItem.importance == newItem.importance
            }
        }
    }
    // your generic code
}