Diffutils with object that has a list of items

661 views Asked by At

Hopefully someone can help me out. How would you go about using diffutils for an object that has a list of objects. So for quick example, may not make sense but to get a better idea.

data class Exercise(
    val name: String,
    var sets: String,
    var bodyTarget: String,
    var weight: String,
)


data class Workout(
    private val workOutId: String,
    private val date: String,
    private val exercises: MutableList<Exercise>
)

Where my adapters data is a list of Workouts. So what I'm not sure about is how I would compare the exercises in the workout class. I guess I would need to compare the exercises one by one inside the areContentsTheSame? Or is there an easier way of accomplishing this

class DiffUtilSample(
private val oldList: List<Workout>,
private val newList: List<Workout>
) : DiffUtil.Callback(){

    override fun areItemsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean =
        oldList[oldItemPosition].workOutId == newList[newItemPosition].workOutId

    override fun getOldListSize(): Int = oldList.size

    override fun getNewListSize(): Int = newList.size

    override fun areContentsTheSame(oldItemPosition: Int, newItemPosition: Int): Boolean {
    //Compare the list of exercises from each workout one by one? So for example I'd compare 
    //the reps, bodyTarget, weight etc 
    }

}

Any help would be appreciated. Thanks!

1

There are 1 answers

0
baltekg On

Because you compare data classes and the objects inside the list is also a data class instances, all you need is to write:

oldList[oldItemPosition] == newList[newItemPosition]

That is because data class automatically overrides equals for you.