我正在我的模型列表中执行一些操作,然后传递给回收器适配器并更新适配器列表。由于某些意外原因,适配器列表在我通过新列表之前已更新。我正在使用 DiffUtil 来计算 oldList 和 newList 之间的差异。
internal fun CheckoutDetailsActivity.updateLineItemWithPartialPayment(lineItemModelToUpdate: LineItemModel){
GlobalScope.launch {
withContext(Dispatchers.Main) {
calculateTodayPayments(lineItemModelToUpdate)
}
}
}
internal suspend fun CheckoutDetailsActivity.calculateTodayPayments(lineItemModelToUpdate: LineItemModel){
var todayPayments: BigDecimal = BigDecimal.ZERO
val lineItems: ArrayList<LineItemModel> = ArrayList(viewModel.ticket?.lineItems)
withContext(Dispatchers.Default){
lineItems.forEachIndexed loop@{ index, lineItemModel ->
if(lineItemModel.id == lineItemModelToUpdate.id){
lineItems[index] = lineItemModelToUpdate
todayPayments += lineItemModelToUpdate.partialPaymentAmount?: BigDecimal.ZERO
return@loop
}
lineItemModel.inPartialPayment = true
todayPayments += lineItemModel.partialPaymentAmount?: BigDecimal.ZERO
}
}
viewModel.todayPayments = todayPayments
updateRecyclerAdapter(lineItems)
showTodayPaymentContainer()
}
internal fun CheckoutDetailsActivity.updateRecyclerAdapter(lineItems: ArrayList<LineItemModel>){
viewModel.lineItemsWithPartialPayment.clear()
viewModel.lineItemsWithPartialPayment.addAll(lineItems)
viewModel.recyclerViewAdapter?.submitList(viewModel.sortLineItems(ArrayList(lineItems)))
viewModel.ticket?.lineItems = lineItems
}
这是我在适配器中的submitList()函数:
fun submitList(lineItemList: List<LineItemModel>){
val oldLineItemList = lineItems
val diffResult: DiffUtil.DiffResult = DiffUtil.calculateDiff(
LineItemDiffCallback(
oldLineItemList,
lineItemList
)
)
this.lineItems.clear()
this.lineItems.addAll(lineItemList)
diffResult.dispatchUpdatesTo(this)
}
class LineItemDiffCallback(
var oldLineItemList: List<LineItemModel>,
var newLineItemList: List<LineItemModel>
): DiffUtil.Callback(){
override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldLineItemList[oldItemPosition].id == newLineItemList[newItemPosition].id
}
override fun getOldListSize(): Int {
return oldLineItemList.size
}
override fun getNewListSize(): Int {
return newLineItemList.size
}
override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
return oldLineItemList[oldItemPosition] == newLineItemList[newItemPosition]
}
}
在最后一种方法中,我使用submitList()更新适配器列表,当我检查viewModel.todayPayments = todayPayments行中的适配器列表时,它已经使用之前的操作“forEachIndexed()”进行了更新,因此 DiffUtil 没有t 工作正常,因为它找不到oldList和newList之间的区别。