Cha*_*fon 4 android kotlin android-recyclerview kotlin-coroutines android-diffutils
我在将 Kotlin Flows 和 async DiffUtil 放在一起时遇到了麻烦。
我的 RecyclerView.Adapter 中有这个函数,它在计算线程上计算一个 DiffUtil 并将更新分派到主线程上的 RecyclerView :
suspend fun updateDataset(newDataset: List<Item>) = withContext(Dispatchers.Default) {
val diff = DiffUtil.calculateDiff(object : DiffUtil.Callback()
{
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean
= dataset[oldItemPosition].conversation.id == newDataset[newItemPosition].conversation.id
override fun getOldListSize(): Int = dataset.size
override fun getNewListSize(): Int = newDataset.size
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean
= dataset[oldItemPosition] == newDataset[newItemPosition]
})
withContext(Dispatchers.Main) {
dataset = newDataset // <-- dataset is the Adapter's dataset
diff.dispatchUpdatesTo(this@ConversationsAdapter)
}
}
Run Code Online (Sandbox Code Playgroud)
我从我的 Fragment 调用这个函数是这样的:
private fun updateConversationsList(conversations: List<ConversationsAdapter.Item>)
{
viewLifecycleOwner.lifecycleScope.launch {
(listConversations.adapter as ConversationsAdapter).updateDataset(conversations)
}
}
Run Code Online (Sandbox Code Playgroud)
updateConversationsList()在很短的时间内被多次调用,因为这个函数是由 Kotlin 的Flowslike调用的Flow<Conversation>。
现在,我有时会遇到java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder错误。阅读这个线程我明白这是一个线程问题,我已经阅读了很多像这样的推荐,都说:更新适配器数据集的线程和调度更新到 RecyclerView 的线程必须相同。
如您所见,我已经通过以下方式尊重这一点:
withContext(Dispatchers.Main) {
dataset = newDataset
diff.dispatchUpdatesTo(this@ConversationsAdapter)
}
Run Code Online (Sandbox Code Playgroud)
由于主线程,只有它,执行这两个操作,我怎么可能得到这个错误?
你的差异是赛车。如果您的更新在短时间内出现两次,这可能会发生:
Adapter has dataset 1 @Main
Dataset 2 comes
calculateDiff between 1 & 2 @Async
Dataset 3 comes
calculateDiff between 1 & 3 @Async
finished calculating diff between 1 & 2 @ Async
finished calculating diff between 1 & 3 @ Async
Dispatcher main starts handling messages
replace dataset 1 with dataset 2 using 1-2 diff @Main
replace dataset 2 with dataset 3 using 1-3 diff @Main - inconsistency
Run Code Online (Sandbox Code Playgroud)
替代方案是 1-3 之间的差异可以在 1-2 之前完成,但问题保持不变。您必须在新计算到来时取消正在进行的计算并防止部署无效的差异,例如在您的片段中存储作业引用:
var updateJob : Job? = null
private fun updateConversationsList(conversations: List<ConversationsAdapter.Item>)
{
updateJob?.cancel()
updateJob = viewLifecycleOwner.lifecycleScope.launch {
(listConversations.adapter as ConversationsAdapter).updateDataset(conversations)
}
}
Run Code Online (Sandbox Code Playgroud)
如果您取消它,withContext(Dispatchers.Main)则会在内部检查继续状态并且不会运行。
| 归档时间: |
|
| 查看次数: |
1216 次 |
| 最近记录: |