java - Android LiveData - 如何在不同的 Activity 中重用相同的 ViewModel?

标签 java android android-livedata

示例 View 模型:

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;
    }

}

主要 Activity :

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);

我想在第二个 Activity 中调用 mModel.getCurrentName().setValue(anotherName); 并让 MainActivity 接收更改。这可能吗?

最佳答案

当您调用 ViewModelProviders.of(this) 时,您实际上创建/保留了一个绑定(bind)到 thisViewModelStore,因此不同的 Activity有不同的 ViewModelStore 并且每个 ViewModelStore 使用给定的工厂创建一个不同的 ViewModel 实例,所以你不能有相同的 实例code>ViewModel 在不同的 ViewModelStore 中。

但您可以通过传递充当单例工厂的自定义 ViewModel 工厂的单个实例来实现此目的,因此它将始终在不同的 Activity 之间传递 ViewModel 的相同实例。

例如:

public class SingletonNameViewModelFactory extends ViewModelProvider.NewInstanceFactory {


    NameViewModel t;

    public SingletonNameViewModelFactory() {
      //  t = provideNameViewModelSomeHowUsingDependencyInjection
    }

    @Override
    public NameViewModel create(Class<NameViewModel> modelClass) {
        return t;
    }
}

因此,您需要制作 SingletonNameViewModelFactory 单例(例如使用 Dagger)并像这样使用它:

mModel = ViewModelProviders.of(this,myFactory).get(NameViewModel.class);

注意:

在不同范围内保留 ViewModel 是一种反模式。强烈建议保留您的数据层对象(例如,使您的数据源或存储库单例)并在不同范围( Activity )之间保留您的数据。

阅读this文章了解详情。

关于java - Android LiveData - 如何在不同的 Activity 中重用相同的 ViewModel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49364550/

相关文章:

java - 使用JPA使用spring和intelliJ连接到数据库

android - 具有共享偏好的 LiveData

java - 安装jdk 7u67后,创建新的Android项目时出错

java - 将 Spark Streaming 中的新值与之前的平均值进行比较

java - 使用 jsoup 抓取数据

android - 是否可以使用嵌套的 ScrollView?

android - 从 Eclipse 到 Android 手机

android - LiveData 适用于回收 View ,但 MutableLiveData 不适用。为什么?

android - 在使用 AndroidX LiveData 和模拟 View 模型进行仪器化测试时遇到问题

java - 使用 log4j-core-2.4.1 时是否需要 log4j-core