Issue
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?
Solution
After diving in the Android Room code, I found out some things:
Room annotation processor generates code from Room annotations (
@Query
,@Insert
...) using javapoet libraryDepending 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 aLiveData
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.
Answered By - Héctor
Answer Checked By - Gilberto Lyons (JavaFixing Admin)