ViewModel如何在配置更改中生存下来

时间:2019-11-17 18:15:21

标签: android mvvm android-architecture-components android-viewmodel

我正在尝试在我的应用中使用ViewModel。我想到的问题是,视图模型如何在配置更改中生存下来。我读了许多博客文章,说“

  

它将创建一个 HolderFragment ,以添加到您的活动或您的活动中   片段,它是不可见的,当配置更改时,活动   已销毁,但持有人片段仍然存在

这很有道理。但是我尝试对此进行更多研究,发现在支持库27.1.0 + 中,他们删除了带有Description的HolderFragment,

  

弃用ViewModelStores.of()及其依赖的 HolderFragment   因为不再需要它们了 link for android.googlesource

现在的问题是他们现在如何做同样的事情?

2 个答案:

答案 0 :(得分:3)

基本上,为了检索ViewModel中的Activity,应该调用ViewModelProviders.of(this).get(SomeViewModel.class)。现在,如果我们查看of,则如下所示:

public static ViewModelProvider of(@NonNull FragmentActivity activity,
        @Nullable Factory factory) {
    Application application = checkApplication(activity);
    if (factory == null) {
        factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
    }
    return new ViewModelProvider(activity.getViewModelStore(), factory);
}

因此,重要的部分是此方法-activity.getViewModelStore(),因为它为所有HashMap对象返回一个包装器对象(ViewModel持有者),并且如果它可以在配置更改中保留下来,那么您所有的ViewModel对象:

public ViewModelStore getViewModelStore() {
    if (getApplication() == null) {
        throw new IllegalStateException("Your activity is not yet attached to the "
                + "Application instance. You can't request ViewModel before onCreate call.");
    }
    if (mViewModelStore == null) {
        NonConfigurationInstances nc =
                (NonConfigurationInstances) getLastNonConfigurationInstance();
        if (nc != null) {
            // Restore the ViewModelStore from NonConfigurationInstances
            mViewModelStore = nc.viewModelStore;
        }
        if (mViewModelStore == null) {
            mViewModelStore = new ViewModelStore();
        }
    }
    return mViewModelStore;
}

mViewModelStore将从NonConfigurationInstances恢复或从头开始创建。几乎NonConfigurationInstances是可以保留配置更改并因此用于存储ViewModelStore的对象。这就是旋转后返回同一ViewModelStore对象的原因-它存储在独立于配置更改的NonConfigurationInstances中:

如果您查看onRetainNonConfigurationInstance(),实际上,您的ViewModelStore将保存在此处:

public final Object onRetainNonConfigurationInstance() {
    ...
    NonConfigurationInstances nci = new NonConfigurationInstances();
    nci.custom = custom;
    nci.viewModelStore = viewModelStore;
    return nci;
}

此外,只有在出于非配置更改原因而调用onDestroy时,才会清除该消息:

...
    getLifecycle().addObserver(new LifecycleEventObserver() {
        @Override
        public void onStateChanged(@NonNull LifecycleOwner source,
                @NonNull Lifecycle.Event event) {
            if (event == Lifecycle.Event.ON_DESTROY) {
                if (!isChangingConfigurations()) {
                    getViewModelStore().clear();
                }
            }
        }
    });
...   

使用类似的技巧为ViewModel存储Fragment

答案 1 :(得分:2)

使用ViewModelProviders.of()方法创建的ViewModels存储在ViewModelStore哈希图中,所以真正的问题是ViewModelStore的存储方式。

对于活动,此逻辑很简单。 ViewModelStore使用onRetainNonConfigurationInstance方法存储:

@Override
    @Nullable
    public final Object onRetainNonConfigurationInstance() {
        Object custom = onRetainCustomNonConfigurationInstance();

        ViewModelStore viewModelStore = mViewModelStore;
        if (viewModelStore == null) {
            // No one called getViewModelStore(), so see if there was an existing
            // ViewModelStore from our last NonConfigurationInstance
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
                viewModelStore = nc.viewModelStore;
            }
        }

        if (viewModelStore == null && custom == null) {
            return null;
        }

        NonConfigurationInstances nci = new NonConfigurationInstances();
        nci.custom = custom;
        nci.viewModelStore = viewModelStore;
        return nci;
    }

对于片段,事情要复杂一些。 FragmentManagerImpl现在有一个名为mNonConfig的字段:

private FragmentManagerViewModel mNonConfig;

存储Fragment的UUID和ViewModelStore的哈希图。

mNonConfig字段是通过FragmentManagerImpl#attachController方法初始化的:

    public void attachController(@NonNull FragmentHostCallback host,
            @NonNull FragmentContainer container, @Nullable final Fragment parent) {
        if (mHost != null) throw new IllegalStateException("Already attached");
        mHost = host;
        mContainer = container;
        mParent = parent;
        if (mParent != null) {
            // Since the callback depends on us being the primary navigation fragment,
            // update our callback now that we have a parent so that we have the correct
            // state by default
            updateOnBackPressedCallbackEnabled();
        }
        // Set up the OnBackPressedCallback
        if (host instanceof OnBackPressedDispatcherOwner) {
            OnBackPressedDispatcherOwner dispatcherOwner = ((OnBackPressedDispatcherOwner) host);
            mOnBackPressedDispatcher = dispatcherOwner.getOnBackPressedDispatcher();
            LifecycleOwner owner = parent != null ? parent : dispatcherOwner;
            mOnBackPressedDispatcher.addCallback(owner, mOnBackPressedCallback);
        }

        // Get the FragmentManagerViewModel
        if (parent != null) {
            mNonConfig = parent.mFragmentManager.getChildNonConfig(parent);
        } else if (host instanceof ViewModelStoreOwner) {
            ViewModelStore viewModelStore = ((ViewModelStoreOwner) host).getViewModelStore();
            mNonConfig = FragmentManagerViewModel.getInstance(viewModelStore);
        } else {
            mNonConfig = new FragmentManagerViewModel(false);
        }
    }