android - Viewmodel 观察 LiveData - 如何?

标签 android mvvm binding android-lifecycle android-livedata

LifecycleLiveData 之前,Viewmodel 可以很容易地观察到它自己的可观察对象的变化。只需订阅 Observable* 的更改并对它们使用react即可。然后可能会使用双向绑定(bind)来立即对用户的输入使用react。

在 Android Studio Canary 中,现在允许绑定(bind)到 LiveData 对象,前提是 Binding 知道其所有者的生命周期(ViewBinding 现在有额外的 setLifecycle 方法),Android Studio Canary information :

You can now use a LiveData object as an observable field in data binding expressions. The ViewDataBinding class now includes a new setLifecycle method that you need to use to use to observe LiveData objects.

然而,Viewmodel documentation明确指出:

ViewModel objects can contain LifecycleObservers, such as LiveData objects. However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects.

(强调我的)

那么如果 ViewModel 无法订阅它们,如何立即对 LiveData 变化使用react?

此外,为什么 Viewmodel 无法观察到它自己的 LiveData 的变化?

最佳答案

我使用 MediatorLiveData 解决了这个问题。您可以按照以下步骤操作。

  1. 创建一个变量(例如结果)。

    private final MediatorLiveData<Resource<RequestType>> result = new MediatorLiveData<>();
    
  2. 调用 addSource 方法,其中第一个参数是 LiveData,第二个是观察者。

    LiveData<Resource<EmptyResponse>> observable = service.createItems();
    result.addSource(observable, response -> {
        //Write code here 
    }
    

另见 this SO answer .基本要求几乎相同。

关于android - Viewmodel 观察 LiveData - 如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48093285/

相关文章:

java - 仅加密图像文件的内容而不是整个文件

android - 如何在android中制作自定义虚线圆形进度条?

c# - 像在 C# 中一样在 C++ 中绑定(bind)

java - 如果没有 MainActivity,我无法使用 getAssets 方法

wpf - 在服务上实现 INotifyCollectionChanged 或 INotifyPropertyChanged 可以吗?

c# - 如何在 viewmodel 方法中更新 busyIndi​​cator 状态?

c# - 按钮没有正确的签名xamarin

c# - Xamarin Forms 观看来自 .xaml.cs 类的 ViewModel 属性

wpf - XAML "Conditional"绑定(bind)

java - 函数发送不可解码的文本 Android/Java