Skip to content

Instantly share code, notes, and snippets.

@netdur
Created May 18, 2016 13:14
Show Gist options
  • Save netdur/d3d529bd74b64726f15885500ac3336b to your computer and use it in GitHub Desktop.
Save netdur/d3d529bd74b64726f15885500ac3336b to your computer and use it in GitHub Desktop.
private var ids = ArrayList<Long>()
fun getIds(results : Any) : ArrayList<Long> {
var ids = ArrayList<Long>()
for (result in results) {
ids.add(result.id)
}
return ids
}
init {
hasStableIds();
ids = getIds(results)
results.onChange {
val newIds = getIds(results)
if (newIds.isEmpty()) {
ids = newIds
notifyDataSetChanged()
return@onChange
}
val patch = DiffUtils.diff(ids, newIds)
val deltas = patch.deltas
ids = newIds
if (!deltas.isEmpty()) {
for (delta in deltas) {
if (delta.type == Delta.TYPE.INSERT) {
notifyItemRangeInserted(delta.revised.position, delta.revised.size())
} else if (delta.type == Delta.TYPE.DELETE) {
notifyItemRangeRemoved(delta.original.position, delta.original.size())
} else if (delta.type == Delta.TYPE.CHANGE) {
notifyItemRangeChanged(delta.revised.position, delta.revised.size())
} else {
notifyDataSetChanged()
}
}
}
}
}
override fun getItemId(position : Int) : Long {
return results[position].id
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment