ViewModel is not observing any data it just returning LiveData object of Product so you can observe the data in ProductFragment
This is how LiveData is observed in ProductFragment, In which the getObservableProduct()
method called on ViewModel which returns LiveData<ProductEntity>
// Observe product data
model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
@Override
public void onChanged(@Nullable ProductEntity productEntity) {
model.setProduct(productEntity);
}
});
This method in ViewModel called from ProductFragment
public LiveData<ProductEntity> getObservableProduct() {
return mObservableProduct;
}
In constructor of that ProductViewModel the member variable mObservableProduct is initialized as follows, Which get LiveData<ProductEntity>
from Repository
private final LiveData<ProductEntity> mObservableProduct;
mObservableProduct = repository.loadProduct(mProductId);
If you dig deeper, in DataRepository, LiveData<ProductEntity>
is fetched from DAO
public LiveData<ProductEntity> loadProduct(final int productId) {
return mDatabase.productDao().loadProduct(productId);
}
And in DAO its nothing but SQL query which returns the LiveData<ProductEntity>
which is implemented by RoomCompiler. As you can see DAO using @Dao annotation which used by annotation processor and Write Dao implementation in ProductDao_Impl
class.
@Query("select * from products where id = :productId")
LiveData<ProductEntity> loadProduct(int productId);
So In a nutshell, ViewModel holding References to all the data required by Activity or Fragment. Data get initialized in ViewModel and it can survive Activity configuration changes. Thus we are storing its references in ViewModel.
In our case LiveData is just wrapper around our object which is returned by DAO implementation as an Observable object. So we can observe this in any Activity or Fragment. So as soon as the data is changed at Data Source, it called postValue()
method on LiveData and we get the callback
Flow of LiveData
DAO -> Repository -> ViewModel -> Fragment