我正在研究Android Architecture Components,我有点困惑 . 在sample中,他们使用存储库并声明ViewModel观察到存储库的数据源内的更改 . 我没有't understand how the changes within the datasource are pushed to the ViewModels, as i cannot see any code within the ViewModels that subscribes them to the repository. Analogously, the fragments observe the ViewModel'的LiveData,但他们实际上订阅了LiveData:
// Observe product data
model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
@Override
public void onChanged(@Nullable ProductEntity productEntity) {
model.setProduct(productEntity);
}
});
我在ViewModels中看不到任何类型的订阅来观察存储库 . 我错过了什么吗?
1 回答
ViewModel is not observing any data 它刚刚返回Product的LiveData对象,因此您可以在ProductFragment中观察数据
这是 LiveData 在ProductFragment中的 observed ,其中
getObservableProduct()
方法在ViewModel上调用,返回LiveData<ProductEntity>
ViewModel中的此方法从ProductFragment调用
在ProductViewModel的构造函数中,成员变量mObservableProduct初始化如下,得到
LiveData<ProductEntity>
from Repository如果你深入挖掘,在DataRepository中,
LiveData<ProductEntity>
被取出 from DAO在DAO中它只有 SQL query ,它返回由 RoomCompiler 实现的
LiveData<ProductEntity>
. 正如你可以看到DAO使用@Dao注释,它由注释处理器和ProductDao_Impl
类中的Write Dao实现使用 .所以在 nutshell , ViewModel holding References 中,要求Activity或Fragment所需的所有数据 . 数据在ViewModel中初始化,并且可以在Activity configuration changes 中存活 . 因此,我们将其引用存储在ViewModel中 . 在我们的例子中,LiveData只是我们的对象的包装,它由DAO实现作为Observable对象返回 . 所以我们可以在任何 Activity or Fragment 中观察到这一点 . 因此,只要在数据源上更改数据,它就会在LiveData上调用
postValue()
方法,我们得到 callbackFlow of LiveData DAO -> Repository -> ViewModel -> Fragment