0

I am trying to use DiffUtil to update a RecyclerView. I have a class DataProvider which is a singleton class that holds the List which contains the Objects.

Every time I need to update the RecyclerView I modify the List in DataProvider. Now when I try to use the DiffUtil which takes two lists as parameters I don't really have the old List anymore, because I updated it.

What is the best way to keep the old List before updating it, so that I can compare them and do the needed updates on the RecyclerView without having to call notifyDataSetChanged()?

Idrizi.A
  • 9,819
  • 11
  • 47
  • 88

1 Answers1

2

Please refer to this answer: https://stackoverflow.com/a/47522246/8298909

I understand that you're asking a different question, but the two code snippets in my linked answer are almost exactly what you're looking for: a simple implementation of DiffUtil.Callback and an example of how to use it even when you're directly modifying the data source that backs your adapter.

The key is to create a (temporary) copy of the pre-modification list by using new ArrayList<>([your data here]) before executing your changes.

Ben P.
  • 52,661
  • 6
  • 95
  • 123
  • Wouldn't that just create a reference to the same `List` and whenever I modify the new list the old one will also get modified? – Idrizi.A Dec 21 '17 at 09:24
  • Because when I check the debugger the Lists both have different IDs for example `ArrayList@5162` and `ArrayList@5163`, but when I check the items inside they all reference to the same object, for example the 1st item in the `oldList` is `Item@5238` which is the same as in the `newList` – Idrizi.A Dec 21 '17 at 11:09
  • @Enve, would you post your solution if you found it ? I am facing the same issue... – Mathieu Jun 07 '19 at 16:59