Should communication with database be so frequent?

from the CommonsWare Community archives

At February 9, 2019, 2:54am, Shahood asked:

Hi,

I’ve a list of objects, lets say, tasks in an app. The Task object has two member variables (among others, of course) namely isFavorite and isLocked. Each task list-item shows a star icon and a lock icon that can be tapped to toggle between favorite/unfavorite and locked/unlocked. On each tap, the icon changes its color to show whether the task is favorite or locked.

I’m using LiveData to get tasks list from Room and populate the ListAdapter. Now what I’m doing is that on each tap of star or lock icon, I update the database with the new value of isFavorite or isLocked as the case may be, which eventually fires onChanged() of the observer, performs the diffing and changes the UI (icon color) accordingly.

While it all is happening seamlessly, for now at least, I wanted to know if it is the most efficient way of doing this? Should we be communicating with the database this frequently? I mean we are on the one hand, writing new values and on the other, getting a new list each time any of those icons is tapped. Also, the diffing is being performed on the whole list each time. Would the performance be hampered if the list grows in size in future, to let’s say a thousand tasks?

Thanks
Shahood


At February 9, 2019, 12:01pm, mmurphy replied:

Probably not. Efficient code is usually harder to program and harder to maintain.

What you need to decide is: is it efficient enough?

That mostly is a matter of testing.

IMHO, you communicate with the database when you are certain that the user wants to persist the data change. In some cases, that is not until the user clicks some sort of “Save”, “Done”, “OK”, or similar thing. In some cases, it might be right away.

There is nothing stopping you from making note of these changes and only updating the database periodically. This is more complicated and more error prone.

If you are referring to RecyclerView and its ListAdapter, or similar things, ideally the “diffing” only pays attention to visible items, which would not change for long lists of model objects.

There is still time involved in loading such a list, but that is where things like the Paging library come into play.

Personally, my opinion is: if the list is so long that it takes noticeable time to load from the database, it is probably longer than the user will want to scroll through, so you should consider a revised UI that is based on searching, category trees, or something else that keeps the lists shorter.