在 Lifecycle
和 LiveData
之前,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
解决了这个问题。您可以按照以下步骤操作。
创建一个变量(例如结果)。
private final MediatorLiveData<Resource<RequestType>> result = new MediatorLiveData<>();
调用
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/