Search code examples
androidandroid-roomandroid-components

What triggers LiveData onChanged()?


I'm using Room and in the Dao I have this method:

LiveData<List<Books>> getAllBooks();

In MainActivity I have subscribed to that method from the ViewModel. Changes to the data trigger the onChanged() callback:

    viewModel.getAllBooks()
            .observe(this, books -> {
                Log.d(TAG, "onChanged()");
                booksListAdapter.setData(new ArrayList<>(books));
            });

What I would like to know is what constitutes an update? When the app first starts I do 100 insertions, each of them changes the database but the onChanged() is not invoked 100 times. Last time I checked it called onChanged() the first time which I think it always calls when starting and then two more calls.

Can I have control over this? For example if I know I will be doing 100 insertions perhaps it would be better if I only got the callback at the end of the insertions.


Solution

  • You don't have control of that. What you can do is use MediatorLiveData and post the value after all insertions. Whenever you update, delete or insert Room knows that there has been change but doesn't know what has been changed. So it just re-queries and sends the results to observing LiveData

    Check this blog and mainly section 7. Avoid false positive notifications for observable queries. Author gives pretty good example of MediatorLiveData which is similar to what you are looking for