JetPack之ViewModel源码解析

作者: 奔跑吧李博 | 来源:发表于2020-08-19 11:00 被阅读0次
    我们认识中的ViewModel是什么

    Viewmodel其实就是activity中一个普通的实体。Activity持有viewmodel的引用,业务逻辑在viewmodel进行,关于界面和ui的操作在activity中进行,而添加和释放资源和viewmodel有关的那么就在viewmodel中设置函数,然后在activity中调用。ViewModel作为Activity/Fragment与其他组件的连接器,负责转换和聚合Model中返回的数据,使这些数据易于显示,并把这些数据改变及时的通知给Activity/Fragment。

    ViewModel的生命周期

    从图中看出,Activity的生命周期不断变化,经历了被销毁重新创建,而ViewModel的生命周期没有发生变化。

    从创建一个viewModel入手分析源码:
    MyViewModel myViewModel = ViewModelProviders.of(this).get(MyViewModel.class);
    

    进入ViewModelProviders.of(this)方法:

        @NonNull
        @MainThread
        public static ViewModelProvider of(@NonNull FragmentActivity activity) {
            return of(activity, null);
        }
    
        @NonNull
        @MainThread
        public static ViewModelProvider of(@NonNull Fragment fragment, @Nullable Factory factory) {
            Application application = checkApplication(checkActivity(fragment));
            if (factory == null) {
                factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
            }
            return new ViewModelProvider(fragment.getViewModelStore(), factory);
        }
    
        @NonNull
        @MainThread
        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);
        }
    

    checkApplication(activity)会获取该activity所属的application。
    ViewModelProvider.AndroidViewModelFactory.getInstance(application)会创建一个单例的AndroidViewModelFactory,并从activity或fragment中获取viewmodelstore,作为两个个参数传入ViewModelProvider构造方法,最后会新建一个ViewModelProvider作为返回。

    ViewModelStore代码实现如下:

    public class ViewModelStore {
    
        private final HashMap<String, ViewModel> mMap = new HashMap<>();
    
        final void put(String key, ViewModel viewModel) {
            ViewModel oldViewModel = mMap.put(key, viewModel);
            if (oldViewModel != null) {
                oldViewModel.onCleared();
            }
        }
    
        final ViewModel get(String key) {
            return mMap.get(key);
        }
    
        Set<String> keys() {
            return new HashSet<>(mMap.keySet());
        }
    
        /**
         *  Clears internal storage and notifies ViewModels that they are no longer used.
         */
        public final void clear() {
            for (ViewModel vm : mMap.values()) {
                vm.clear();
            }
            mMap.clear();
        }
    }
    

    ViewModelStore类通过hashmap来存储和移除Viewmodel。

    AndroidViewModelFactory类代码如下:

        public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {
    
            private static AndroidViewModelFactory sInstance;
    
            /**
             * Retrieve a singleton instance of AndroidViewModelFactory.
             *
             * @param application an application to pass in {@link AndroidViewModel}
             * @return A valid {@link AndroidViewModelFactory}
             */
            @NonNull
            public static AndroidViewModelFactory getInstance(@NonNull Application application) {
                if (sInstance == null) {
                    sInstance = new AndroidViewModelFactory(application);
                }
                return sInstance;
            }
    
            private Application mApplication;
    
            /**
             * Creates a {@code AndroidViewModelFactory}
             *
             * @param application an application to pass in {@link AndroidViewModel}
             */
            public AndroidViewModelFactory(@NonNull Application application) {
                mApplication = application;
            }
    
            @NonNull
            @Override
            public <T extends ViewModel> T create(@NonNull Class<T> modelClass) {
                if (AndroidViewModel.class.isAssignableFrom(modelClass)) {
                    //noinspection TryWithIdenticalCatches
                    try {
                        return modelClass.getConstructor(Application.class).newInstance(mApplication);
                    } catch (NoSuchMethodException e) {
                        throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                    } catch (InstantiationException e) {
                        throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                    } catch (InvocationTargetException e) {
                        throw new RuntimeException("Cannot create an instance of " + modelClass, e);
                    }
                }
                return super.create(modelClass);
            }
        }
    

    ViewModel是抽象类,AndroidViewModel继承于ViewModel,AndroidViewModelFactory从它的create方法可以看出,通过反射生成ViewModel的实现类。

    get(MyViewModel.class)部分

    进入到了ViewModelProvider进行执行,ViewModelProvider代码如下:

    public class ViewModelProvider {
    
        private static final String DEFAULT_KEY =
                "androidx.lifecycle.ViewModelProvider.DefaultKey";
    
            public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
            mFactory = factory;
            mViewModelStore = store;
        }
    
        @NonNull
        @MainThread
        public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
            String canonicalName = modelClass.getCanonicalName();    //注释1
            if (canonicalName == null) {
                throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
            }
            return get(DEFAULT_KEY + ":" + canonicalName, modelClass);  //注释2
        }
    
        @NonNull
        @MainThread
        public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
            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).create(modelClass);
            }
            mViewModelStore.put(key, viewModel);
            //noinspection unchecked
            return (T) viewModel;
        }
    }
    

    过程分析:注释1处得到类的名称,对这个名称进行字符串拼接,拼接上前缀androidx.lifecycle.ViewModelProvider.DefaultKey,作为注释2处方法的参数,作为key值去ViewModelStore中获取viewmodel实例。如果ViewModel能转换为modelClass类的对象,直接返回该ViewModel。否则就会通过AndroidViewModelFactory的create方法通过反射创建一个ViewModel,并将其存储到ViewModelStore中。

    相关文章

      网友评论

        本文标题:JetPack之ViewModel源码解析

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