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?
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.
After diving in the Android Room code, I found out some things:
Room annotation processor generates code from Room annotations (@Query
, @Insert
...) using javapoet library
Depending on the result type of the query (QueryMethodProcessor), it uses a "binder" or another one. In the case of LiveData
, it uses LiveDataQueryResultBinder.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With