DiffUtil ItemCallback areContentsTheSame() always returns true after updating an item on the ListAdapter

人盡茶涼 提交于 2020-02-21 13:53:46

问题


While using a ListAdapter I noticed that after updating an item the DiffUtil.ItemCallback areContentsTheSame() method was always returning true. Debugging the code I realized that the old and the new item were exactly the same (the old state disappeared). Therefore the ListAdapter onBindViewHolder() method wasn't being called to update the respective row on the list (only the order of the items changed with a nice animation).

Checking other questions on Stackoverflow looks like it's a common issue that many developers have faced:

ListAdapter not updating item in reyclerview

ListAdapter not updating when editing content

DiffUtil.Callback not working as expected

Items in Recyclerview + Listadapter won't redraw on update

ListAdapter with DiffUtil.ItemCallback always considers objects the same

When submitting a new list to RecyclerView ListAdapter the diff check always returns true for areContentsTheSame()

However none of the above answers (if any) have provided a correct solution.

The only way it worked for me was by calling notifyDataSetChanged() on the ListAdapter everytime the observer emitted a new result.

But what's the whole point of using a ListAdapter and submitList() to notify changes if all the great performance you could get is thrown away by forcing the RecyclerView to redraw its content (all the items it has showed so far)?

  1. notifyDataSetChanged():

Even though it works, certainly is not the proper approach to go with if you decided to use a ListAdapter in first place.

  1. viewModel.getObjects().observe(this, listOfObjects -> listAdapter.submitList(new ArrayList<>(listOfObjects)));:

Didn't work.

After updating a item in the list I would like to see the respective changes taking place on the UI (not only the sorting order) for the corresponding row as expected.


回答1:


I spent a lot of time until I found out that I was having the same issue as described on this post. I tried many solutions, but in the end I realised that I was messing it up without knowing. If you're having this same issue, check if you aren't updating the UI first and calling a write command to update the value on your repository. In my case, I was updating the LiveData object and then updating that value on Firebase Database. The issue was being caused because my UI was listening to changes on that LiveData object, so my Firebase Database observer detected changes, the ListAdapter was called and it looked like nothing has been changed.

To solve the problem, I dropped the lines that were updating the LiveData object and I only called Firebase Database sending the changes.



来源:https://stackoverflow.com/questions/57876118/diffutil-itemcallback-arecontentsthesame-always-returns-true-after-updating-an

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!