Johann
Johann

Reputation: 29875

LiveData updates my observable when changes occur in Room database

I use LiveData to display the count of records in a table in Room. I call a function that retrieves this count and upon receiving it the observer is called which displays the count. This works as expected. But I also have a service running that retrieves data from the backend and stores it in the same table that I read the count from. But whenever the data gets stored, the observable gets called each time and the displayed count gets updated. I'm not sure why this happens. I do in fact want this to happen. I just don't understand why it is happening. When I run my code to retrieve the count, it is done using RxJava. So when the call completes, I don't see any reason why the observable for the count would be updated with each data storage. The only possible reason is that Room keeps track of my query for the count and executes it whenever data is stored. Is that possible? Here is my code on getting the count:

Observed in my fragment:

viewModel.onConnectionsCountRetrieved.observe(this, Observer { count ->
    var title = getString(R.string.connections)

    if (count > 0)
        title += " (" + "%,d".format(count) + ")"

    (activity as MainActivity).getSupportActionBar()?.title = title
})

In my viewmodel:

val onConnectionsCountRetrieved: MutableLiveData<Int> = MutableLiveData()

@SuppressLint("CheckResult")
fun getConnectionsCount() {
    val disposable = connectionsBO.getConnectionsCount()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            { count -> onConnectionsCountRetrieved.postValue(count) },
            { ex -> App.context.displayErrorMessage(R.string.problem_retrieving_total_connection_count) }
        )

    disposables.add(disposable)
}

Upvotes: 0

Views: 1389

Answers (1)

FedeFonto
FedeFonto

Reputation: 354

From Room documentations:

Observable queries

When performing queries, you'll often want your app's UI to update automatically when the data changes. To achieve this, use a return value of type LiveData in your query method description. Room generates all necessary code to update the LiveData when the database is updated.

Room offers also the same functionality for RxJava. You can see the implementation of your query in the generated class YourDao_Impl.java.

Upvotes: 5

Related Questions