Android 架构组件:ViewModel 如何观察存储库中的 LiveData

Android Architecture Components: How is LiveData in the repository observed by a ViewModel

我正在研究 Android Architecture Components and i'm a little bit confused. In the sample 他们使用一个存储库和状态,ViewModel 观察到存储库数据源内的变化。我不明白数据源中的更改是如何推送到 ViewModel 的,因为我看不到 ViewModel 中将它们订阅到存储库的任何代码。类似的,fragments观察的是ViewModel的LiveData,但实际上订阅的是LiveData:

 // Observe product data
    model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
        @Override
        public void onChanged(@Nullable ProductEntity productEntity) {
            model.setProduct(productEntity);
        }
    });

我在 ViewModel 中看不到任何类型的订阅以观察存储库。我错过了什么吗?

ViewModel 未观察任何数据 它只是返回 Product 的 LiveData 对象,因此您可以观察 ProductFragment

中的数据

这就是 LiveDataProductFragmentobserved 的方式,其中 getObservableProduct() 方法调用了 ViewModel其中 returns LiveData<ProductEntity>

// Observe product data
    model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
        @Override
        public void onChanged(@Nullable ProductEntity productEntity) {
            model.setProduct(productEntity);
        }
    });

ViewModel 中的此方法从 ProductFragment

调用
public LiveData<ProductEntity> getObservableProduct() {
    return mObservableProduct;
}

ProductViewModel 的构造函数中,成员变量 mObservableProduct 初始化如下,从 Repository

中获取 LiveData<ProductEntity>
private final LiveData<ProductEntity> mObservableProduct;
mObservableProduct = repository.loadProduct(mProductId);

如果你深入挖掘,在 DataRepository 中,LiveData<ProductEntity> 是从 DAO

中获取的
public LiveData<ProductEntity> loadProduct(final int productId) {
    return mDatabase.productDao().loadProduct(productId);
}

在 DAO 中它只是 SQL 查询 其中 returns LiveData<ProductEntity>RoomCompiler。如您所见,DAO 使用@Dao 注释,注释处理器和 Write Dao 实现在 ProductDao_Impl class.

中使用
@Query("select * from products where id = :productId")
LiveData<ProductEntity> loadProduct(int productId);

所以在 nutshell 中,ViewModel 持有对 Activity 或 Fragment 所需的所有数据的引用。数据在 ViewModel 中初始化,它可以在 Activity 配置更改 后继续存在。因此我们将其引用存储在 ViewModel 中。 在我们的例子中,LiveData 只是我们对象的包装器,它由 DAO 实现作为 Observable 对象返回。所以我们可以在任何 Activity 或 Fragment 中观察到这一点。因此,一旦数据源处的数据发生更改,它就会调用 LiveData 上的 postValue() 方法,我们得到 回调

LiveData 的

Flow DAO -> 存储库 -> ViewModel -> 片段