Android 架构组件:ViewModel 如何观察 Repository 中的 LiveData

4
我正在学习Android Architecture Components,现在有点糊涂了。在示例中,他们使用了一个仓库,并声明仓库数据源的更改会被ViewModels观察到。我不理解数据源中的更改如何推送到ViewModels中,因为我无法在ViewModels中看到任何代码订阅它们到仓库。类似地,片段观察ViewModels的LiveData,但实际上是订阅LiveData。
 // Observe product data
    model.getObservableProduct().observe(this, new Observer<ProductEntity>() {
        @Override
        public void onChanged(@Nullable ProductEntity productEntity) {
            model.setProduct(productEntity);
        }
    });

我在ViewModels中没有看到任何订阅来观察Repository。我是否漏掉了什么?

您可能还想查看以下关于使用MVVM和LiveData构建电影搜索应用程序的示例:http://www.digigene.com/android-architecture-part-5-mvvm-with-livedata-wolfkcats - Ali Nem
1个回答

10

ViewModel没有观察到任何数据,它只返回Product的LiveData对象,因此您可以在ProductFragment中观察数据。

这是在ProductFragment中观察LiveData的方法,在其中调用了ViewModel上的getObservableProduct()方法,该方法返回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的初始化如下,它从存储库获取LiveData<ProductEntity>
private final LiveData<ProductEntity> mObservableProduct;
mObservableProduct = repository.loadProduct(mProductId);

如果你深入挖掘DataRepositoryLiveData<ProductEntity>会从DAO中获取

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

在DAO中,它仅仅是一个SQL查询,返回由RoomCompiler实现的LiveData<ProductEntity>。如您所见,DAO使用@Dao注解,该注解由注解处理器使用,并在ProductDao_Impl类中编写DAO实现。

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

简而言之,ViewModel持有对Activity或Fragment所需的所有数据的引用。 数据在ViewModel中初始化并且可以在Activity配置更改后保持不变。 因此我们将其引用存储在ViewModel中。 在我们的情况下,LiveData只是我们在DAO实现中返回的Observable对象的包装器。 因此,我们可以在任何Activity或Fragment中观察它。 因此,当数据源中的数据发生更改时,会在LiveData上调用postValue()方法,然后我们得到回调。 LiveData的流程为:DAO-> Repository-> ViewModel-> Fragment。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接