gpt4 book ai didi

android - DiffUtilCallBack 用于搜索或过滤列表时是否需要使用协程暂停 DiffUtilCallBack?

转载 作者:太空狗 更新时间:2023-10-29 14:35:24 25 4
gpt4 key购买 nike

fun updateItems(
newItems: List<T>?,
itemSame: (T, T) -> Boolean,
contentSame: (T, T) -> Boolean
) {
val diffResult =
DiffUtil.calculateDiff(DiffCalc(this.items, newItems!!, itemSame, contentSame))
diffResult.dispatchUpdatesTo(this)
items = newItems
}

使用协程暂停此操作是一种好习惯吗?

最佳答案

根据列表中的项目数,DiffUtil.calculateDiff 可能需要很长时间才能执行(超过允许的 16 毫秒)。由于您不想阻塞 UI 线程,因此最好将此函数调用移动到另一个线程,然后在 UI 线程上分派(dispatch)结果。

当然,您可以使用任何您喜欢的技术:AsyncTask、RxJava Schedulers,或使用 withContext(Dispatchers.Default) 移动到另一个协程上下文。但是这种模式太常见了,它已经在 RecyclerView 库中实现了:ListAdapter .当使用submitList更新ListAdapter的项目时,差异是在后台线程上计算的,你不需要调用calculateDiff dispatchUpdatesTo 了。

关于android - DiffUtilCallBack 用于搜索或过滤列表时是否需要使用协程暂停 DiffUtilCallBack?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57195491/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com