Skip to content

Instantly share code, notes, and snippets.

@kubode
Created July 20, 2017 12:45
Show Gist options
  • Save kubode/d2922d0c26160a53955e0143e422bb35 to your computer and use it in GitHub Desktop.
Save kubode/d2922d0c26160a53955e0143e422bb35 to your computer and use it in GitHub Desktop.
DiffUtilを使ってRecyclerView.Adapterをいい感じにする ref: http://qiita.com/kubode/items/92c1190a6421ba055cc0
interface Diffable {
// otherと同じIDを持つかどうか
fun isTheSame(other: Diffable): Boolean = equals(other)
// otherと完全一致するかどうか
fun isContentsTheSame(other: Diffable): Boolean = equals(other)
}
private class Callback(
val old: List<Diffable>,
val new: List<Diffable>
) : DiffUtil.Callback() {
override fun getOldListSize() = old.size
override fun getNewListSize() = new.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return old[oldItemPosition].isTheSame(new[newItemPosition])
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return old[oldItemPosition].isContentsTheSame(new[newItemPosition])
}
}
fun calculateDiff(
old: List<Diffable>,
new: List<Diffable>,
detectMoves: Boolean = false
): DiffUtil.DiffResult {
return DiffUtil.calculateDiff(Callback(old, new), detectMoves)
}
class MyAdapter : RecyclerView.Adapter<AbstractViewHolder>() {
var items: List<Item> by Delegates.observable(emptyList()) { _, old, new ->
calculateDiff(old, new).dispatchUpdatesTo(this)
}
}
val adapter = MyAdapter()
recyclerView.adapter = adapter
adapter.items = listOf(Item(0, "Item: 0"))
recyclerView.postDelayed({ adapter.items += Item(1, "Item: 1") }, 1000)
data class Item(val id: Long, val fullName: String) : Diffable {
override fun isTheSame(other: Diffable) = id == (other as? Item)?.id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment