使用DiffUtil时更改List中的特定项



在这种情况下,
当有一个列表有100个项目,只想改变其中的一些,我是否需要创建一个新的列表与DiffUtil比较?

fun fetchDynamicItems() {
val items = repository.fetchOnlyDynamicItems()
replaceDynamicItems(items)
}
fun replaceDynamicItems(dynamicItems: List<DynamicItem>) {
val oldList = getCurrentList()
val newList = getCurrentList().map {
when (it) {
is DynamicItem -> dynamicItems.get(matchedIndex)
else -> it
}
}
// newList will be a copied list except DynamicItem
adapter.submitList(newList)
}

是否有一个好方法来使用DiffUtil只改变几个项目,而不创建一个新的列表?

不,你必须创建一个新的列表。否则,它将无法比较新旧版本。

注意,一般来说,创建一个新列表是微不足道的。在两个链表中属于同一实例的项各只多占用一个单词的内存,因为两个链表只保存对相同实例的引用。

最新更新