I don't know if this is the solution for this specific case, but by the description it sounds exactly like something I went through very recently.
I am working with a new Room + LiveData + ViewModel + DiffUtils integration for the first time and I was having the same problem with updating the items in a RecyclerView after updating the list.
The problem I was having was due to my understanding of updating a list and allowing DiffUtils to do its job as it should. Hopefully the following will be clear enough:
What I was doing:
- User updates its item using a dialog
- The list item in the RecyclerView is updated with the new information
- Room triggers the LiveData observer because something might have
changed
- The RecyclerView DiffUtils tries to check any differences between
the old adapter list and the new one
- Nothing new was detected
- The Adapter is not triggered to update its UI
My mistake was thinking that the problem was in .5 which caused me to spend half a day going back and forth debugging the problem. Eventually I stumbled upon a SO question (cannot find it at the moment) which lead me to the correct source of the problem. That problem is really located in .2 - updating the item in the list.
This is the problem because we are updating our CURRENT adapter list with the new changes even before DiffUtils has a chance of comparing the old and new list changes. What this means is every single time the DiffUtils was always comparing the lists with the old list already containing the changes the new list had.
The solution? Do not update the list item since it is an object and list objects keep the same reference resulting in the same instance being updated everywhere that it is being used/referenced.
Instead clone the item object (as in deep clone, I know this might be annoying), apply the changes the user made to that cloned object and then use that clone to update the item entry in the Room Database.
DO NOT replace the adapter list item with the clone, leave the original one alone, we only want to update the information in the database, not the list since DiffUtils will take care of that.
What we are essentially doing here is creating an update payload for our Room Database, which will then trigger the LiveData observer into comparing the old list with the new one (containing the updated item data) resulting in the expected change detection between both lists.
In short;
Do this:
- Deep clone adapter list item
- Update only the clone with the new information
- Update the database with the clone information
Don't do this:
- Update the adapter list item directly
- Update the database with the list item information
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…