Android LiveData-如何在不同活动中重用相同的ViewModel? [英] Android LiveData - how to reuse the same ViewModel on different activities?
问题描述
ViewModel示例:
Example ViewModel:
public class NameViewModel extends ViewModel {
// Create a LiveData with a String
private MutableLiveData<String> mCurrentName;
public MutableLiveData<String> getCurrentName() {
if (mCurrentName == null) {
mCurrentName = new MutableLiveData<>();
}
return mCurrentName;
}
}
主要活动:
mModel = ViewModelProviders.of(this).get(NameViewModel.class);
// Create the observer which updates the UI.
final Observer<String> nameObserver = textView::setText;
// Observe the LiveData, passing in this activity as the LifecycleOwner and the observer.
mModel.getCurrentName().observe(this, nameObserver);
我想在第二个活动中调用mModel.getCurrentName().setValue(anotherName);
,并使MainActivity接收更改.有可能吗?
I want to call mModel.getCurrentName().setValue(anotherName);
in second activity and make MainActivity receive changes. Is that possible?
推荐答案
调用ViewModelProviders.of(this)
时,实际上创建/保留了绑定到this
的ViewModelStore
,因此不同的活动具有不同的ViewModelStore
和每个ViewModelStore
使用给定的工厂创建ViewModel
的不同实例,因此您不能在不同的ViewModelStore
中具有相同的ViewModel
实例.
When you call ViewModelProviders.of(this)
, you actually create/retain a ViewModelStore
which is bound to this
, so different Activities have different ViewModelStore
and each ViewModelStore
creates a different instance of a ViewModel
using a given factory, so you can not have the same instance of a ViewModel
in different ViewModelStore
s.
但是您可以通过传递自定义ViewModel工厂的单个实例(充当单例工厂)来实现此目的,因此它将始终在不同活动之间传递您ViewModel
的相同实例.
But you can achieve this by passing a single instance of a custom ViewModel factory which acts as a singleton factory, so it will always pass the same instance of your ViewModel
among different activities.
例如:
public class SingletonNameViewModelFactory extends ViewModelProvider.NewInstanceFactory {
NameViewModel t;
public SingletonNameViewModelFactory() {
// t = provideNameViewModelSomeHowUsingDependencyInjection
}
@Override
public NameViewModel create(Class<NameViewModel> modelClass) {
return t;
}
}
因此,您需要制作SingletonNameViewModelFactory
单身人士(例如,使用Dagger)并像这样使用它:
So what you need is to make SingletonNameViewModelFactory
singleton (e.g. using Dagger) and use it like this:
mModel = ViewModelProviders.of(this,myFactory).get(NameViewModel.class);
注意:
在不同范围之间保留ViewModel
是一种反模式.强烈建议保留您的数据层对象(例如,使您的DataSource或Repository单例)并在不同范围(活动)之间保留数据.
Preserving ViewModel
s among different scopes is an anti-pattern. It's highly recommended to preserve your data-layer objects (e.g. make your DataSource or Repository singleton) and retain your data between different scopes (Activities).
有关详细信息,请阅读这篇文章.
Read this article for details.
这篇关于Android LiveData-如何在不同活动中重用相同的ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!