Sobes.tech
Middle

How would you create adapters for use with DiffUtil?

sobes.tech AI

Answer from AI

// Example of a basic adapter with DiffUtil support
class MyListAdapter : RecyclerView.Adapter<MyListAdapter.MyViewHolder>() {

    private var items: List<MyItem> = emptyList() // Current data list

    // Method to update the data list using DiffUtil
    fun updateItems(newItems: List<MyItem>) {
        val diffResult = DiffUtil.calculateDiff(MyDiffCallback(items, newItems))
        items = newItems // Update the internal list
        diffResult.dispatchUpdatesTo(this) // Notify adapter of changes
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        // Create ViewHolder
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_layout, parent, false)
        return MyViewHolder(view)
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        // Bind data to ViewHolder
        val item = items[position]
        holder.bind(item)
    }

    override fun getItemCount(): Int {
        return items.size // Return list size
    }

    // Inner ViewHolder class
    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        private val textView: TextView = itemView.findViewById(R.id.item_text_view)

        fun bind(item: MyItem) {
            textView.text = item.name // Example of binding data
        }
    }

    // Class implementing DiffUtil.Callback
    private class MyDiffCallback(
        private val oldList: List<MyItem>,
        private val newList: List<MyItem>
    ) : DiffUtil.Callback() {

        override fun getOldListSize(): Int = oldList.size

        override fun getNewListSize(): Int = newList.size

        // Determine if two items are the same (by identifier)
        override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList[oldItemPosition].id == newList[newItemPosition].id
        }

        // Determine if the contents of two items are the same
        override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
            return oldList[oldItemPosition] == newList[newItemPosition] // Use default or overridden equals
        }

        // Optionally override getChangePayload if needed
    }
}