0

i want to update a list item with diffUtils but after i set list with diffDiffUtils like this:

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

diff util doesn't update recyclerView items so i use a function like this:

fun updateItem(item: Model) {
    val index = itemList.indexOfFirst {
        it.id == item.id
    }
   itemList[index].enabled = item.enabled
   notifyItemChanged(index)
}
  • 1
    Use ListAdapter as your RecyclerView’s Adapter. You pass the DiffUtil callback to its constructor. Then all you need to do is call `submitList` on the adapter with the new list of data each time something changes, and it automatically updates the RecyclerView. – Tenfour04 Oct 03 '21 at 18:54

1 Answers1

1

Easiest Way will be using a ListAdapter and passing your DiffUtil.ItemCallback to it ref , example

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
}
Anshul
  • 1,495
  • 9
  • 17