Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does LiveData know when data is changed in Room Database?

Tags:

android

mvvm

I am learning Mvvm pattern in android, and I don't understand one thing. How Live Data knows when data has changed in Room Database? I have this code:

Fragment:

 newUserViewModel.getListItemById(itemId).observe(this, new Observer<User>() {
        @Override
        public void onChanged(@Nullable User user) {
            tv.setText(user.getName());
        }
    });

View model:

 public LiveData<User> getListItemById(String itemId){       
    return repository.getListItem(itemId);
}

Repository:

 public LiveData<User> getListItem(String itemId){
    return userDao.getUSerByID(itemId);
}

DAO:

@Query("SELECT * FROM User WHERE itemId = :itemId")
LiveData<User> getUSerByID(String itemId);// When this query gets executed and how live Data knows that our Table is changed?

let's say we inserted new User in Database. When is @Query("SELECT * FROM User WHERE itemId = :itemId") gets executed when there is new data in our database?) and How LiveData knows that we have new User in table and callback Observer owner that data has changed?

like image 670
Nikolas Bozic Avatar asked Jan 29 '18 08:01

Nikolas Bozic


People also ask

How do you observe mutable live data?

In MutableLiveData we can observe and set the values using postValue() and setValue() methods (the former being thread-safe) so that we can dispatch values to any live or active observers. MediatorLiveData can observe other LiveData objects such as sources and react to their onChange() events.


1 Answers

After diving in the Android Room code, I found out some things:

  1. Room annotation processor generates code from Room annotations (@Query, @Insert...) using javapoet library

  2. Depending on the result type of the query (QueryMethodProcessor), it uses a "binder" or another one. In the case of LiveData, it uses LiveDataQueryResultBinder.

  3. LiveDataQueryResultBinder generates a LiveData class that contains a field _observer of type InvalidationTracker.Observer, responsible of listen to database changes.

Then, basically, when there is any change in the database, LiveData is invalidated and client (your repository) is notified.

like image 55
Héctor Avatar answered Sep 22 '22 23:09

Héctor