odifek
odifek

Reputation: 190

Recyclerview ListAdapter DiffUtil not working as expected

My diffcallback areContentsTheSame(oldItem: ItemModel, newItem: ItemModel) always receives the same content. I use the status to check, but each time the status is the same. Even though the status is actually changing. I intend to display progress for each item. So I regularly send the current progress through a status. Using diffcallback, it should check that status for an item are not the same and then update that item only. But it seems newItem and oldItem it receives are same.

I have a custom model ItemModel

data class ItemModel(val id: String, var title: String) {

    var clickListener: ClickListener? = null
    var status: Status? = null

    interface ClickListener{
        fun onItemClick(view: View, item: ItemModel)
        fun onClick(view: View, item: ItemModel)
    }

    companion object {
        val STATUS_CHANGED = 1

        val diffCallback = object : DiffUtil.ItemCallback<ItemModel>() {
            override fun areItemsTheSame(oldItem: ItemModel, newItem: ItemModel): Boolean {
//                Log.i("DiffUtil", "SameItem? old status: ${oldItem.status}, new Status: ${newItem.status}")
                return oldItem.id == newItem.id
            }

            override fun areContentsTheSame(oldItem: ItemModel, newItem: ItemModel): Boolean {
//                Log.i("DiffUtil", "Checking status: new: ${newItem.status}, old ${oldItem.status}")
                return oldItem.status == newItem.status
            }

            override fun getChangePayload(oldItem: ItemModel, newItem: ItemModel): Any? {
                Log.i("DiffUtil", "Payload change: ${newItem.status?.state}")
                if (oldItem.status != newItem.status) {
                    return STATUS_CHANGED
                }
                return null
            }

        }
    }
}

And Status data class

data class Status(val max: Int, val progress: Int, val state: State = State.NONE)

This is my ViewModel class; I use Observable.intervalRange to generate different numbers and change the status of a single list item. But it seems that diffcallback is not working properly.

class FunViewModel : ViewModel() {

    private val itemModels: MutableLiveData<List<ItemModel>> = MutableLiveData()

    fun items(): LiveData<List<ItemModel>> {
        return itemModels
    }

    private val compositeDisposable = CompositeDisposable()

    fun initialize(itemList: List<ItemModel>) {
        itemModels.value = itemList
    }

    private fun updateItem(item: ItemModel, status: Status) {
        val currentItems = mutableListOf<ItemModel>()
        if (itemModels.value == null) return
        currentItems.addAll(itemModels.value!!)

        Log.i("UpdateItem", "Current item: ${item.id}")

        if (currentItems.isNotEmpty()) {
            for ((index, el) in currentItems.withIndex()) {
//                Log.i("UpdateItem", "searching: ${el.id}")
                if (el.id == item.id) {
                    val currentItem = currentItems.removeAt(index)
                    Log.i("UpdateItem", "old status: ${currentItem.status}")
                    currentItem.status = status
                    currentItems.add(index, currentItem)
                    break
                }
            }
            itemModels.value = currentItems
            Log.i("UpdateItem", "new status: ${items().value?.get(0)?.status}")
        }
    }

    fun startProgress(item: ItemModel) {
        val disposable = getProgress(item.id).map { progress ->
            val status = Status(progress.second.toInt(), progress.third.toInt(), State.IN_PROGRESS)
            status
        }.subscribeOn(Schedulers.single())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe({ status ->
                updateItem(item, status)
//                Log.i("FunViewModel:", "Status: progress: ${status.progress}, State: ${status.state}")
            },
                { throwable: Throwable? -> Log.e("FunViewModel", "Unable to process progress!", throwable) },
                {
                    val status = Status(20, 20, State.COMPLETED)
                    updateItem(item, status)
                    Log.i("FunViewModel:", "Status: progress: ${status.progress}, State: ${status.state}")
                })
        compositeDisposable.add(disposable)
    }


    private fun getProgress(id: String): Observable<Triple<String, Long, Long>> {
        return Observable.intervalRange(0, 20, 300, 500, TimeUnit.MILLISECONDS)
            .map { num -> Triple<String, Long, Long>(id, 20, num) }
    }

    override fun onCleared() {
        super.onCleared()
        if (!compositeDisposable.isDisposed) compositeDisposable.dispose()
    }
}

Upvotes: 3

Views: 2580

Answers (1)

odifek
odifek

Reputation: 190

Well, I discovered the problem was that I was copying the original contents in a way that does not do actual content copy but referencing. So I fixed the problem by copying the item contents into a new itemModel instance. With this done, diff util is able to differentiate properly.

Instead of this,

private fun updateItem(item: ItemModel, status: Status) {
       ......................................................


            for ((index, el) in currentItems.withIndex()) {
                if (el.id == item.id) {
                    val currentItem = currentItems.removeAt(index)

                    currentItem.status = status
                    currentItems.add(index, currentItem)
                    break
                }
            }
            itemModels.value = currentItems
          ......................................
    }

I did this,

private fun updateItem(item: ItemModel, status: Status) {
...............
    if (el.id == item.id) {
         currentItems.removeAt(index)
         val currentItem = ItemModel(item.id, "${item.title}, ${status.progress}")
         currentItem.status = status
         currentItems.add(index, currentItem)
         break
     }
...........
}

Upvotes: 2

Related Questions