示例视图模型:
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 接收更改。那可能吗?
原文由 user1209216 发布,翻译遵循 CC BY-SA 4.0 许可协议
When you call
ViewModelProviders.of(this)
, you actually create/retain aViewModelStore
which is bound tothis
, so different Activities have differentViewModelStore
and eachViewModelStore
creates a different instance of aViewModel
using a given factory, so you can not have the same instance of aViewModel
in differentViewModelStore
s。但是您可以通过传递充当单例工厂的自定义 ViewModel 工厂的单个实例来实现此目的,因此它将始终在不同的活动中传递您的
ViewModel
的相同实例。例如:
所以你需要做的是制作
SingletonNameViewModelFactory
单例(例如使用Dagger)并像这样使用它:笔记:
在不同范围之间保留
ViewModel
是一种反模式。强烈建议保留您的数据层对象(例如,使您的数据源或存储库单例)并在不同范围(活动)之间保留您的数据。阅读 这篇 文章了解详情。