Viewmode原理

作者: 小红军storm | 来源:发表于2021-06-10 23:10 被阅读0次

    1. Viewmode优势

    ViewModel旨在以注重生命周期的方式存储和管理界面相关的数据(配合它里面的livedata)。

    1.1 将Activity的UI处理和数据处理分离,分开管理,解耦且高效。

    1.2 ViewModel在屏幕旋转等系统配置更改后被继续保留,避免再次请求数据,浪费网络资源。重建该 Activity时,它接收的ViewModel实例与之前的Activity持有的ViewModel相同。

    只有当Activity真正销毁时,框架才会调用getViewModelStore().clear()清除所有的ViewModel。

    1.3 避免页面销毁后,数据返回后刷新界面导致crash,例如页面发起请求后,数据还没返回就关闭activity,数据返回后,刷新界面,因view不存在而crash。

    1.4 两个Fragment可以使用其Activity的ViewModel来处理通信。

    1.5 和onSaveInstanceState()对比,onSaveInstanceState()仅适合可以序列化再反序列化的少量数据,而不适合数量可能较大的数据,如用户列表或位图。

    1.6 ViewModelScope,为应用中的每个ViewModel定义了ViewModelScope。如果ViewModel已清除,则在此范围内启动的协程都会自动取消。

    2. 传递数据到ViewModel中

    // 创建一个ViewModel类,带有参数
    class ViewModelDemo(var str:String) : ViewModel() {
    
        var liveData = MutableLiveData<Int>(4)
    }
    
    //通过ViewModelProvider的工厂类创建一个带有参数的ViewModel
       var viewModelDemo = ViewModelProvider(this, object : ViewModelProvider.Factory {
                override fun <T : ViewModel?> create(modelClass: Class<T>): T {
                    return ViewModelDemo("test") as T
                }
    
            }).get(ViewModelDemo::class.java)
    

    3. ViewModelProvider获取ViewModel

    3.1 ViewModelProvider构造方法

    //通过构造方法的调用链,我们可以看到最终都是调用了第三个构造方法
        public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
            this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
                    ? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
                    : NewInstanceFactory.getInstance());
        }
    
        public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
            this(owner.getViewModelStore(), factory);
        }
    
        public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
            mFactory = factory;
            mViewModelStore = store;
        }
        
        
        public class ComponentActivity extends androidx.core.app.ComponentActivity implements
            ContextAware,
            LifecycleOwner,
            ViewModelStoreOwner,
            HasDefaultViewModelProviderFactory,
            SavedStateRegistryOwner,
            OnBackPressedDispatcherOwner,
            ActivityResultRegistryOwner,
            ActivityResultCaller 
    

    ViewModelStoreOwner:是一个接口,ComponentActivity和Fragment实现了这个接口,所以我们在Activity或者Fragment中使用ViewModelProvider传入的this就可以了。

    ViewModelStore:ViewModelStore主要是用来存储ViewModel对象的,内部有一个HashMap集合用来存储ViewModel对象。

    ComponentActivity持有一个ViewModelStore,可以通过ViewModelStoreOwner中的getViewModelStore()方法获取。(为啥不直接在Activity获取ViewModelStore,再获取ViewModel呢?因为ViewModel要通过ViewModelProvider.Factory创建)

    Factory:是一个接口,用来创建ViewModel的

    3.2 ViewModelProvider #get()

        @MainThread
        public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
            String canonicalName = modelClass.getCanonicalName();
            if (canonicalName == null) {
                throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
            }
            //构造了一个key
            return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
        }
    
        @MainThread
        public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
            ViewModel viewModel = mViewModelStore.get(key);
    
            if (modelClass.isInstance(viewModel)) {
                if (mFactory instanceof OnRequeryFactory) {
                    ((OnRequeryFactory) mFactory).onRequery(viewModel);
                }
                return (T) viewModel;
            } else {
                //noinspection StatementWithEmptyBody
                if (viewModel != null) {
                    // TODO: log a warning.
                }
            }
            if (mFactory instanceof KeyedFactory) {
                viewModel = ((KeyedFactory) (mFactory)).create(key, modelClass);
            } else {
                viewModel = (mFactory).create(modelClass);
            }
            mViewModelStore.put(key, viewModel);
            return (T) viewModel;
        }
    

    调用get方法后,会调用第二个get方法,传递key(DEFAULT_KEY + ":" + canonicalName)给第二个get方法

    首先根据提供的key从ViewModelStore中获取一个ViewModel对象

    如果这个获取到的ViewModel对象实例存在,那么就将其返回

    如果该ViewModel对象不存在,就通过Factory创建一个ViewModel对象,并将其存储到ViewModelStore中,并将这个新创建的ViewModel对象返回。

    这里面存在三个Factory:Factory,KeyedFactory和OnrequeryFactory,keyedFactory和Factory相比就是create方法中多了一个key参数。

    ViewModelStore获取到ViewModel时,会判断当前mFactory是否是OnRequeryFactory类型的,是的话会回调onRequery方法

    那么OnRequeryFactory回调onRequery有什么用呢?其实ViewModel不仅可以因为配置改变可以恢复Activity数据,也能恢复因为系统资源紧张而回收掉的Activity数据,只不过后者需要依靠SaveStateHandler

    总结:ViewModelProvider获取到ViewModel:

    1,首先创建ViewModelProvider传入ViewModelStoreOwner和Factory
    2,调用ViewModelProvider的get方法,从ViewModelStore中获取ViewModel,有则直接返回,没有就通过反射创建一个,加入ViewModelStore中后,返回。

    4. ViewModel的恢复

    ViewModel是从ViewModelStore中获取

    ViewModelStore是通过ViewModelStoreOwner.getViewModelStore方法获取

    ComponentActivity实现了ViewModelStoreOwner接口和HasDefaultViewModelProviderFactory

    4.1 ComponentActivity # getViewModelStore()

        @Override
        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.");
            }
            ensureViewModelStore();
            return mViewModelStore;
        }
    
        void ensureViewModelStore() {
            if (mViewModelStore == null) {
                NonConfigurationInstances nc =
                        (NonConfigurationInstances) getLastNonConfigurationInstance();
                if (nc != null) {
                    // Restore the ViewModelStore from NonConfigurationInstances
                    mViewModelStore = nc.viewModelStore;
                }
                if (mViewModelStore == null) {
                    mViewModelStore = new ViewModelStore();
                }
            }
        }
    

    getViewModelStore()通过两种方法获取到ViewModelStore

    1,从NonConfigurationInstances中拿到

    2,new一个出来

    NonConfigurationInstances,用来包装不受配置更改影响的数据

    Activity的NonConfigurationInstances在系统配置改变时保存了ViewModelStore和fragments等

    4.2 ActivityThread #handleRelaunchActivity

    系统配置发生改变时,AMS会调用ActivityThread的handleRelaunchActivity,并且通过当前Activity对应的ActivityRecord构建一个ActivityClientRecord传递过来

    Activity的生命周期方法是在ActivityThread中执行的

    private void handleRelaunchActivity(ActivityClientRecord tmp) {
    
        ActivityClientRecord r = mActivities.get(tmp.token);
        ...
        //注意最后一个参数getNonConfigInstance为true,如果是正常退出Activity的走到onDestory的该参数为false
        handleDestroyActivity(r.token, false, configChanges, true);
        ...
        handleLaunchActivity(r, currentIntent, "handleRelaunchActivity");
    }
    
    private void handleDestroyActivity(IBinder token, boolean finishing,
            int configChanges, boolean getNonConfigInstance) {
        ActivityClientRecord r = performDestroyActivity(token, finishing,
                    configChanges, getNonConfigInstance);
    }
    

    4.2 ActivityThread #performDestroyActivity

    ActivityClientRecord performDestroyActivity(IBinder token, boolean finishing,
                int configChanges, boolean getNonConfigInstance, String reason) {
                 ....
                 
                //注意此时ActivityClientRecord并未从mActivities中移除,只有执行完Destroy才会移除
                ActivityClientRecord r = mActivities.get(token);
                performPauseActivityIfNeeded(r, "destroy");
    
                if (!r.stopped) {
                      //执行Activity的onStop()方法
                    callActivityOnStop(r, false /* saveState */, "destroy");
                }
                /此时为true,正常退出的为false
                if (getNonConfigInstance) {
                    try {
                        //调用对应Activity的retainNonConfigurationInstances方法
                        //返回值NonConfigurationInstance赋给ActivityClientRecord内的lastNonConfigurationInstances持有
                        r.lastNonConfigurationInstances
                                = r.activity.retainNonConfigurationInstances();
                    } catch (Exception e) {
                        if (!mInstrumentation.onException(r.activity, e)) {
                          ...
                        }
                    }
                }
               
              /最终回调到onDestroy方法
              mInstrumentation.callActivityOnDestroy(r.activity);
              ...
        }
    

    Activity的retainNonConfigurationInstances 调用了onRetainNonConfigurationInstance

    4.3 ComponentActivity # onRetainNonConfigurationInstance()

    public final Object onRetainNonConfigurationInstance() {
            // Maintain backward compatibility.
            Object custom = onRetainCustomNonConfigurationInstance();
    
            ViewModelStore viewModelStore = mViewModelStore;
            if (viewModelStore == null) {
                // No one called getViewModelStore(),从lastNonConfigurationInstance取出viewModelStore
                NonConfigurationInstances nc =
                        (NonConfigurationInstances) getLastNonConfigurationInstance();
                if (nc != null) {
                    viewModelStore = nc.viewModelStore;
                }
            }
    
            if (viewModelStore == null && custom == null) {
                return null;
            }
            
            //创建一个NonConfigurationInstances,将此时的mViewModelStore设置进去
            NonConfigurationInstances nci = new NonConfigurationInstances();
            nci.custom = custom;
            nci.viewModelStore = viewModelStore;
            return nci;
        }
    
    

    在调用onDestory()方法前,会创建一个NonConfigurationInstances对象,将viewModelStore存储在NonConfigurationInstances,然后将NonConfigurationInstances存储在ActivityClientrecord中。

    4.4 ActivityThread #performLaunchActivity

    private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {
    ...
        activity.attach(appContext, this, getInstrumentation(), r.token,
                            r.ident, app, r.intent, r.activityInfo, title, r.parent,
                            r.embeddedID, r.lastNonConfigurationInstances, config,
                            r.referrer, r.voiceInteractor, window, r.configCallback,
                            r.assistToken);
    }
    ...
    

    ActivityThread的handleLaunchActivity最终会调用
    performLaunchActivity,最终调用到activity.attach,传入了lastNonConfigurationInstances

    这样对于新的Activity来说,获取到的就是之前Activity的NonConfigurationInstance,其中的ViewModelStore也是之前的,ViewModel自然也是之前的。

    这样就保证了在系统配置改变时,ViewModel不变了。

    总结:

    1,系统配置改变时,构建一个NonConfigurationInstance,将ViewModelStore保持到NonConfigurationInstance,再将NonConfigurationInstance保存到ActivityClientrecord的lastNonConfigurationInstances

    2,恢复时,将ActivityClientrecord的lastNonConfigurationInstances传递给新的Activity,再通过getViewModelStore()获取时就能从新的Activity的lastNonConfigurationInstances获取ViewModelStore,进而获取之前的ViewModel

    (1,系统配置发生改变时,调用handleRelaunchActivity,在这个方法中会先取出activity对应的ActivityClientrecord,然后调用handleDestroyActivity,在这个方法中,会调用ComponentActivity 的onRetainNonConfigurationInstance(),在这个方法中,会构建一个NonConfigurationInstance,将ViewModelStore保持到NonConfigurationInstance,再将NonConfigurationInstance保存到ActivityClientrecord的lastNonConfigurationInstances

    2,恢复时,调用到handleLaunchActivity,在这个方法中会调用activity.attach方法,在这个方法中,将ActivityClientrecord的lastNonConfigurationInstances传递给新的Activity的lastNonConfigurationInstances变量。获取ViewModelStore时,会从Activity的lastNonConfigurationInstances去获取(如果没有就新创建一个)如果有的话,自然就是之前的ViewModelStore,里面的ViewModel自然也是之前的。)

    5. Activity正常销毁

    public ComponentActivity() {
        getLifecycle().addObserver(new LifecycleEventObserver() {
                @Override
                public void onStateChanged(@NonNull LifecycleOwner source,
                        @NonNull Lifecycle.Event event) {
                    if (event == Lifecycle.Event.ON_DESTROY) {
                        // Clear out the available context
                        mContextAwareHelper.clearAvailableContext();
                        // And clear the ViewModelStore
                        if (!isChangingConfigurations()) {
                            getViewModelStore().clear();
                        }
                    }
                }
            });
        }
    

    Activity正常销毁时,会通过getViewModelStore().clear()清理所有的ViewModel。

    6. 参考

    1,https://www.jianshu.com/p/e2cc680d5829
    2,https://developer.android.com/topic/libraries/architecture/viewmodel?hl=zh-cn
    3,https://juejin.cn/post/6873356946896846856

    相关文章

      网友评论

        本文标题:Viewmode原理

        本文链接:https://www.haomeiwen.com/subject/ygtmeltx.html