I'm performing some operations in my model list to be passed after to recycler adapter and update the adapter list. For some unexpected reason the adapter list has been updated before i pass the new list. I'm using DiffUtil to calculate the difference between an oldList and 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
}
this is my submitList() function in the adapter:
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]
}
}
In the last method i'm updating the adapter list with submitList(), when i check the adapter list in viewModel.todayPayments = todayPayments line it has been already updated with the previous operation "forEachIndexed()", for that reason DiffUtil doesn't works correctly, because it can't find difference between oldList and newList.