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

FiX*_*XiT 11 android mvvm android-viewmodel android-architecture-components

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

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

这是有道理的。但我试图对此进行更多探索,并发现在支持库 27.1.0+ 中,他们已经删除了 HolderFragment 和 Description 说

弃用 ViewModelStores.of() 和它依赖HolderFragment ,因为它们不再需要android.googlesource 的链接

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

Sta*_*lov 14

使用ViewModelProviders.of()方法创建的 ViewModel存储在ViewModelStorehashmap 中,所以真正的问题是如何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;
    }
Run Code Online (Sandbox Code Playgroud)

对于片段,事情有点复杂。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);
        }
    }
Run Code Online (Sandbox Code Playgroud)


Ana*_*lii 8

基本上,为了检索ViewModelActivity一个应该调用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);
}
Run Code Online (Sandbox Code Playgroud)

所以,重要的部分是这个方法 -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;
}
Run Code Online (Sandbox Code Playgroud)

mViewModelStoreNonConfigurationInstances从头开始恢复或从头创建。几乎NonConfigurationInstances是在配置更改后仍然存在的对象,因此用于存储ViewModelStore. 这就是为什么ViewModelStore在旋转后返回相同的对象 - 它存储在配置更改独立中NonConfigurationInstances

如果您查看onRetainNonConfigurationInstance(),您实际上会发现您ViewModelStore已保存在那里:

public final Object onRetainNonConfigurationInstance() {
    ...
    NonConfigurationInstances nci = new NonConfigurationInstances();
    nci.custom = custom;
    nci.viewModelStore = viewModelStore;
    return nci;
}
Run Code Online (Sandbox Code Playgroud)

此外,只有在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();
                }
            }
        }
    });
...   
Run Code Online (Sandbox Code Playgroud)

类似的技巧用于存储 a ViewModelfor a Fragment