![](/img/trans.png)
[英]Using Delegates.observable with StateFlow in Kotlin(Android)
[英]How do I get the difference between old and new data using Delegates.Observable?
獲得差異而不是返回整個值以重繪UI會更好嗎?
var collection: List<String> by
Delegates.observable(emptyList()) { prop, old, new ->
notifyDataSetChanged()
}
有可能提高效率嗎?
您應該看一下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)
}
一些參考:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.