与返回UI重绘所需的全部值相比,获取差异不是更好吗?
var collection: List<String> by
Delegates.observable(emptyList()) { prop, old, new ->
notifyDataSetChanged()
}有可能提高效率吗?
发布于 2018-07-19 08:24:49
您应该看看DiffUtil类
DiffUtil是一个实用工具类,它可以计算两个列表之间的差异,并输出一个更新操作列表,将第一个列表转换为第二个列表。 DiffUtil使用Eugene W. Myers的差分算法计算将一个列表转换为另一个列表的最小更新数。Myers的算法不处理被移动的项,因此DiffUtil对结果进行第二次传递,以检测已移动的项。 如果列表很大,则此操作可能需要大量时间,因此建议您在后台线程上运行此操作,
基本上,您必须使用两个列表实现一个DiffUtil.Callback,
data class MyPojo(val id: Long, val name: String)
class DiffCallback(
private val oldList: List<MyPojo>,
private val newList: List<MyPojo>
) : DiffUtil.Callback() {
override fun getOldListSize() = oldList.size
override fun getNewListSize() = newList.size
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].id == newList[newItemPosition].id
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldList[oldItemPosition].name == newList[newItemPosition].name
}
override fun getChangePayload(oldItemPosition: Int, newItemPosition: Int): Any? {
// Implement method if you're going to use ItemAnimator
return super.getChangePayload(oldItemPosition, newItemPosition)
}
}然后,您必须通知适配器使用它。例如,您可以在适配器中创建如下函数:
fun swap(items: List<myPojo>) {
val diffCallback = ActorDiffCallback(this.items, items)
val diffResult = DiffUtil.calculateDiff(diffCallback)
this.items.clear()
this.items.addAll(items)
diffResult.dispatchUpdatesTo(this)
}(在您的例子中是),假设collection是适配器的成员:
var collection: List<String> by Delegates.observable(emptyList()) { prop, old, new ->
val diffCallback = DiffCallback(old, new)
val diffResult = DiffUtil.calculateDiff(diffCallback)
diffResult.dispatchUpdatesTo(this)
}一些参考资料:
https://stackoverflow.com/questions/51417646
复制相似问题