5

I have a project that loads a list from the server. This data will eventually be stored into a database, but for now is stored in memory in a MutableLiveData. A RecyclerView's adapter is watching the data and displaying it. So far everything is working as expected, using a FAB the user can post a new entry which will go at the top of the list, on success I get a 200 and here's the main part where I'm getting lost...

When I want to add a single item to a list stored in a LiveData, the observer is unaware of the delta. I currently make a call to RecyclerView.Adapter.notifyDataSetChanged(), though the ideal in my case would be to call notifyItemInserted(0) or in other cases I can see various other notifications. What the best way to do this? The lifecycle architecture library appears to be very well thought of, I assume I'm missing something simple. I can't imagine having to manually perform a diff between the lists?

Rob
  • 2,243
  • 4
  • 29
  • 40
TheHebrewHammer
  • 3,018
  • 3
  • 28
  • 45
  • Hi on adding new data post the data to server on receiving success from server add the object into list and call notifyDataSetChanged() – Shanmugam Oct 05 '17 at 12:35
  • Yes, that works but is very wasteful as the entire RecyclerView will be re-calculated. Calling `notifyItemInserted` also allows to trigger the insert animation and is much more desirable. – TheHebrewHammer Oct 05 '17 at 12:36
  • Where is the issue? You are adding an item to the list so you know the position. – Murat Karagöz Oct 05 '17 at 12:50
  • Not always, let's say it's a discussion board, someone else could have posted a comment. When I comment yes, it goes at the top/bottom depending on how I chose to order, but this is a good time to sync. I might want to trigger a fresh GET that might insert other users' comments in other spots. – TheHebrewHammer Oct 05 '17 at 12:57
  • see [this](https://developer.android.com/topic/libraries/architecture/paging.html) - *"That newly-created PagedList is sent to the PagedListAdapter on the UI thread. The PagedListAdapter then uses DiffUtil on a background thread to compute the difference between the current list and the new list. When the comparison is finished, the PagedListAdapter uses the list difference information to make appropriate call to RecyclerView.Adapter.notifyItemInserted() to signal that a new item was inserted."* – pskink Oct 05 '17 at 13:04

0 Answers0