AndroidX设计架构MVVM之ViewModel创建流程原理分析

本文基于ViewModel 2.1.0,分析在activity中ViewModel创建流程原理分析
原文

AndroidX设计架构MVVM之ViewModel创建流程原理分析
AndroidX设计架构MVVM之ViewModel生命周期分析
AndroidX设计架构MVVM之LiveDatal生命周期及数据监听分析
AndroidX设计架构MVVM之DataBinding搭配LiveData的分析
AndroidX设计架构MVVM之DataBinding+ViewModel+LiveData

activity中的使用如下,本文不做详细使用说明

 mViewModel = ViewModelProviders.of(this).get(getVmClass());

ViewModel的创建分两步走:1>创建并初始化ViewModelProvider,2>根据VMClass创建ViewModel

1—创建并初始化ViewModelProvider

    @NonNull
    @MainThread
    public static ViewModelProvider of(@NonNull FragmentActivity activity,
            @Nullable Factory factory) {
        Application application = checkApplication(activity);
        if (factory == null) {
        //**分析点3**
            factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
        }
         //**分析点4**
        return new ViewModelProvider(activity.getViewModelStore(), factory);
    }

分析点3:由于传入的factory 为空,会走到这里创建一个AndroidViewModelFactory,流程见代码中的注释。

 public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {

        private static AndroidViewModelFactory sInstance;
        @NonNull
        public static AndroidViewModelFactory getInstance(@NonNull Application application) {
            if (sInstance == null) {
                sInstance = new AndroidViewModelFactory(application);
            }
            return sInstance;
        }

        private Application mApplication;
   
        public AndroidViewModelFactory(@NonNull Application application) {
            mApplication = application;
        }

        @NonNull
        @Override
        public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
           // 判断是否为AndroidViewModel的子类
            if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
                //noinspection TryWithIdenticalCatches
                try {
                //通过AndroidViewModel子类带Application的构造函数创建实例
                    return modelClass.getConstructor(Application.class).newInstance(mApplication);
                } catch (NoSuchMethodException e) {
                 。。。。。。。
                }
            }
            return super.create(modelClass);
        }
    }
}

分析点4:初始化ViewModelProvider
创建或获取已有的ViewModelStore,其实是对HashMap的简单封装。

 return new ViewModelProvider(activity.getViewModelStore(), factory);

//返回已有的ViewModelStore,或者重新创建
 public ViewModelStore getViewModelStore() {
          。。。。。
        if (mViewModelStore == null) {
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
            if (nc != null) {
               //分析点5
                // Restore the ViewModelStore from NonConfigurationInstances
                mViewModelStore = nc.viewModelStore;
            }
            if (mViewModelStore == null) {
            // 内部是一个value为ViewModel的HashMap
                mViewModelStore = new ViewModelStore();
            }
        }
        return mViewModelStore;
    }

分析点5:这个和ViewModel的生命周期有关,可以参考ViewModel生命周期分析

2—根据VMClass创建ViewModel

进入第一步创建ViewModelProvider的get()方法,返回已有的mViewModelStore,或者创建ViewModel并保存在mViewModelStore中,再返回。也就是说一个Activity中只有一个mViewModelStore,里边保存了多个ViewModel

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");
        }
        return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
    }
    
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
       //key为ViewModel 的唯一标识
        ViewModel viewModel = mViewModelStore.get(key);
       //
        if (modelClass.isInstance(viewModel)) {
            //noinspection unchecked
            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为注意点3上创建的AndroidViewModelFactory
            viewModel = (mFactory).create(modelClass);
        }
        //存储ViewModel
        mViewModelStore.put(key, viewModel);
        //noinspection unchecked
        return (T) viewModel;
    }

总结:
1 若activity首次加载,则ViewModelProviders通过of()方法创建了AndroidViewModelFactory和ViewModelStore,ViewModelProvider的get()方法则通过AndroidViewModelFactory创建一个ViewModel,并保存在ViewModelStore中供之后使用。
2 一个activity中只有一个ViewModelStore,ViewModelStore中保存此activity中所有ViewModel。

你可能感兴趣的:(Android)