Skip to content

Instantly share code, notes, and snippets.

@hector6872
Last active November 22, 2018 09:49
Show Gist options
  • Save hector6872/6b6a5c67993c314504edb6ce6b5a5620 to your computer and use it in GitHub Desktop.
Save hector6872/6b6a5c67993c314504edb6ce6b5a5620 to your computer and use it in GitHub Desktop.
AdapterUpdatable for Kotlin (RecyclerView+DiffUtil)
interface AdapterUpdatable<TYPE> {
companion object {
private const val DEFAULT_UPDATE_CURRENT_LIST = false
}
val list: MutableList<TYPE>
fun update(
newList: List<TYPE>,
updateCurrentList: Boolean = DEFAULT_UPDATE_CURRENT_LIST,
comparatorToUpdateCurrentList: (TYPE, TYPE) -> Boolean = { x, y -> x == y }
) {
update(this as RecyclerView.Adapter<*>, list, newList, updateCurrentList, comparatorToUpdateCurrentList)
}
private fun update(
adapter: RecyclerView.Adapter<*>,
oldList: MutableList<TYPE>,
newList: List<TYPE>,
updateCurrentList: Boolean,
comparatorToUpdateCurrentList: (TYPE, TYPE) -> Boolean
) {
if (updateCurrentList) {
adapter.update(oldList, newList, comparatorToUpdateCurrentList)
} else {
update(newList)
}
adapter.notifyDataSetChanged()
}
private fun RecyclerView.Adapter<*>.update(
oldList: List<TYPE>,
newList: List<TYPE>,
comparator: (TYPE, TYPE) -> Boolean
) {
val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback() {
override fun areItemsTheSame(
oldItemPosition: Int,
newItemPosition: Int
): Boolean = comparator(oldList[oldItemPosition], newList[newItemPosition])
override fun areContentsTheSame(
oldItemPosition: Int,
newItemPosition: Int
): Boolean = oldList[oldItemPosition] == newList[newItemPosition]
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
})
update(newList)
diff.dispatchUpdatesTo(this)
}
private fun update(newList: List<TYPE>) {
list.run {
clear()
addAll(newList)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment