Last active
July 1, 2021 04:24
-
-
Save cesarferreira/99a2d82b5c0887c2aa48219057ab55e2 to your computer and use it in GitHub Desktop.
DiffUtils kotlin extension
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class DeliveryWindowsAdapter : RecyclerView.Adapter<DeliveryWindowsAdapter.ViewHolder>() { | |
var items: List<DeliveryWindowUiModel> by Delegates.observable(emptyList()) { _, oldList, newList -> | |
autoNotify(oldList, newList) { o, n -> o.id == n.id } | |
} | |
override fun onBindViewHolder(holder: ViewHolder, position: Int) { | |
val deliveryWindow = items[position] | |
holder.title.text = deliveryWindow.title | |
holder.price.text = deliveryWindow.friendlyPrice | |
} | |
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { | |
val itemView = LayoutInflater.from(parent.context).inflate(R.layout.book_delivery_item_cell, parent, false) | |
return ViewHolder(itemView) | |
} | |
override fun getItemCount(): Int = items.size | |
inner class ViewHolder(v: View) : RecyclerView.ViewHolder(v) { | |
val title: TextView = v.titleTextView | |
val price: TextView = v.priceTextView | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example | |
import android.support.v7.util.DiffUtil | |
import android.support.v7.widget.RecyclerView | |
fun <T> RecyclerView.Adapter<*>.autoNotify(oldList: List<T>, newList: List<T>, compare: (T, T) -> Boolean) { | |
val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() { | |
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { | |
return compare(oldList[oldItemPosition], newList[newItemPosition]) | |
} | |
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean { | |
return oldList[oldItemPosition] == newList[newItemPosition] | |
} | |
override fun getOldListSize() = oldList.size | |
override fun getNewListSize() = newList.size | |
}) | |
diff.dispatchUpdatesTo(this) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fun updateList(list: List<DeliveryUiModel>) { | |
theAdapter.items = list | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment