Android 我如何使用委托获得新旧数据之间的差异。可观察?
获取差异而不是返回整个UI值以重新绘制不是更好吗Android 我如何使用委托获得新旧数据之间的差异。可观察?,android,kotlin,delegates,observable,Android,Kotlin,Delegates,Observable,获取差异而不是返回整个UI值以重新绘制不是更好吗 var collection: List<String> by Delegates.observable(emptyList()) { prop, old, new -> notifyDataSetChanged() } var集合:列表依据 可观察的(emptyList()){prop,旧的,新的-> notifyDataSetChanged() } 有可能提高效率吗?你应该看看课堂 DiffUtil是一
var collection: List<String> by
Delegates.observable(emptyList()) { prop, old, new ->
notifyDataSetChanged()
}
var集合:列表依据
可观察的(emptyList()){prop,旧的,新的->
notifyDataSetChanged()
}
有可能提高效率吗?你应该看看课堂
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)
}
var collection: List<String> by Delegates.observable(emptyList()) { prop, old, new ->
val diffCallback = DiffCallback(old, new)
val diffResult = DiffUtil.calculateDiff(diffCallback)
diffResult.dispatchUpdatesTo(this)
}