Skip to content

Instantly share code, notes, and snippets.

@programmerr47
Created December 29, 2019 11:24
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 programmerr47/e33b1a3bebe7af9881ce70057e6aa6d0 to your computer and use it in GitHub Desktop.
Save programmerr47/e33b1a3bebe7af9881ce70057e6aa6d0 to your computer and use it in GitHub Desktop.
Basic and simple DiffCallback as a default diff calculation and abstract ListDiffCallback as a powerful instrument for fast diff building
typealias DiffCallbackFactory<T> = (List<T>, List<T>) -> DiffUtil.Callback
class SimpleDiffCallback<T : Any>(
private val oldList: List<T>,
private val newList: List<T>
) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldPos: Int, newPos: Int) = oldList[oldPos] == newList[newPos]
override fun areContentsTheSame(oldPos: Int, newPos: Int) = oldList[oldPos] == newList[newPos]
}
abstract class ListDiffCallback<T>(
private val oldList: List<T>,
private val newList: List<T>
) : DiffUtil.Callback() {
final override fun getOldListSize() = oldList.size
final override fun getNewListSize() = newList.size
final override fun areItemsTheSame(oldPos: Int, newPos: Int) =
areItemsTheSame(oldList[oldPos], newList[newPos])
final override fun areContentsTheSame(oldPos: Int, newPos: Int) =
areContentsTheSame(oldList[oldPos], newList[newPos])
abstract fun areItemsTheSame(old: T, new: T): Boolean
open fun areContentsTheSame(old: T, new: T) = old == new
protected fun any(vararg conditions: Boolean) = conditions.any { it }
protected inline fun <reified T> same(that: Any, other: Any, filter: (T) -> Any): Boolean =
same<T>(that, other) { that, other -> filter(that) == filter(other) }
protected inline fun <reified T> same(that: Any, other: Any, compare: (T, T) -> Boolean = { _, _ -> true }) =
that is T && other is T && compare(that, other)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment