I have noticed some strange behavior from the android Room library (at least it looks strange to me).
While there are other posts with similar problems, none of them (that I could find) are quite the same as this.
My issue is that when I observe a LiveData
object, my observers' onChange()
method is called multiple times but only for INSERT operation. The method will be triggered once for every object I insert (i.e. if I insert a list of N objects, it will be triggered N times), whereas for other operations (such as DELETE) it is fired once no matter the size of the list I am deleting.
I have the following queries in my DAO:
@query("select * from myTable")
LiveData<myEntity> getAll();
@insert
void insert(List<myEntity> entities);
@delete
void delete(List<myEntity> entities);
I am observing the getAll()
method and I am definitely calling the delete()
and insert()
methods one time - something like this:
public void insertAll(List<myEntity> items)
{
myDao.insert(items);
}
and
public void deleteAll(List<myEntity> items)
{
myDao.delete(items);
}
Since in my onChange()
method I am updating a RecyclerView
adapter which is visible to the user, this is a problem as I am getting a lot of duplicates and also I am doing some other things in there which should really only be done once every time the table changes but instead they are executed many times (as I've said, once for every item inserted).
I have read this article and tried to implement tip number 7 but the problem persists. https://medium.com/google-developers/7-pro-tips-for-room-fbadea4bfbd1
Is this by design and considered normal behavior? What can I do to have my observer only fire once for every INSERT operation (even if I insert multiple objects at the same time)?