Skip to content

Instantly share code, notes, and snippets.

@Kondenko
Last active June 24, 2019 14:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Kondenko/5b50cdf8f7c70e9a2e4f88db39510b92 to your computer and use it in GitHub Desktop.
Save Kondenko/5b50cdf8f7c70e9a2e4f88db39510b92 to your computer and use it in GitHub Desktop.
A delegate to update RecycletView's adapter data with DiffUtil
class DiffUtilDelegate<T, VH : RecyclerView.ViewHolder, A : RecyclerView.Adapter<VH>>(
initialValue: List<T>,
private val callbackFactory: (List<T>, List<T>) -> DiffUtil.Callback =
{ old, new -> SimpleCallback(old, new) }
) {
private var currentValue: List<T> = initialValue
operator fun setValue(thisRef: A?, property: KProperty<*>, value: List<T>) {
val callback = callbackFactory(currentValue, value)
val diff = DiffUtil.calculateDiff(callback)
thisRef?.let { diff.dispatchUpdatesTo(it) }
currentValue = value
}
operator fun getValue(thisRef: Any?, property: KProperty<*>): List<T> = currentValue
}
class SimpleCallback<T>(
private val oldList: List<T>,
private val newList: List<T>,
private val areItemsTheSame: ((oldItem: T, newItem: T) -> Boolean)? = null,
private val areContentsTheSame: ((oldItem: T, newItem: T) -> Boolean)? = null,
private val getChangePayload: ((oldItem: T, newItem: T) -> Any?)? = null
) : DiffUtil.Callback() {
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return areItemsTheSame?.invoke(
oldList[oldItemPosition],
newList[newItemPosition]
) ?: oldList[oldItemPosition] == newList[newItemPosition]
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return areContentsTheSame?.invoke(
oldList[oldItemPosition],
newList[newItemPosition]
) ?: oldList[oldItemPosition] == newList[newItemPosition]
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
return getChangePayload?.invoke(oldList[oldItemPosition], newList[newItemPosition])
}
override fun getOldListSize(): Int = oldList.size
override fun getNewListSize(): Int = newList.size
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment