Skip to content
Advertisement

How to update only changed item with MutableLiveData in Android?

I have nested fragments with ViewPager2 and Tabs, and I’m loading data into RecyclerView with MutableLiveData. Everything works fine till I update something on my Firebase Realtime Database (eg. name of some food item). So if I have 10 category items with each having 5 food items, and I update name of 1 food, my screen flickers and 10 new categories are added with each having 5 food items and now I have total 20 categories..

Desired behaviour would be: Update data, no screen flickers, just updating changed item WITHOUT adding all that categories and food lists all over again

So how could I achieve that my MutableLiveData would update just changed item, not whole list?

ViewModel

JavaScript

MenuFragment

JavaScript

CategoryModel

JavaScript

Advertisement

Answer

If you attach a ValueEventListener to a location, you get called with a snapshot of all data at that location each time anything is modified under it.

Your onDataChange adds the items in the snapshot to tempList whenever that happens. So on the initial load it adds the 10 categories. Then when there’s a change, it adds them again and you end up with 20 categories.

The simplest way to get rid of the duplicate items, is to clear the list before adding the items to it:

JavaScript

This gets rid of the duplicates, but will probably still result in some flicker as you’re forcing Android to repaint the entire list. If you also want to get rid of that, consider using addChildEventListener. With that type of listener you get notified of the changes to the individual child node, and can use that information to perform a minimal update to tempList, which you can then also tell Android to perform by calling notifyItemChanged and similar methods. This is pretty much what the adapters in FirebaseUI do.

Advertisement