首页 文章

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

提问于
浏览
1

我正在研究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 回答

  • 6

    ViewModel is not observing any data 它刚刚返回Product的LiveData对象,因此您可以在ProductFragment中观察数据

    这是 LiveDataProductFragment中的 observed ,其中 getObservableProduct() 方法在ViewModel上调用,返回 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> from Repository

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

    如果你深入挖掘,在DataRepository中, LiveData<ProductEntity> 被取出 from DAO

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

    在DAO中它只有 SQL query ,它返回由 RoomCompiler 实现的 LiveData<ProductEntity> . 正如你可以看到DAO使用@Dao注释,它由注释处理器和 ProductDao_Impl 类中的Write Dao实现使用 .

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

    所以在 nutshellViewModel holding References 中,要求Activity或Fragment所需的所有数据 . 数据在ViewModel中初始化,并且可以在Activity configuration changes 中存活 . 因此,我们将其引用存储在ViewModel中 . 在我们的例子中,LiveData只是我们的对象的包装,它由DAO实现作为Observable对象返回 . 所以我们可以在任何 Activity or Fragment 中观察到这一点 . 因此,只要在数据源上更改数据,它就会在LiveData上调用 postValue() 方法,我们得到 callback

    Flow of LiveData DAO -> Repository -> ViewModel -> Fragment

相关问题