Android架构——ViewModel源码学习总结

本文是楼主学习ViewModel 源码的一些总结,感觉ViewModel的源码是Android 三大架构中 最容易理解的一个了。

本文内容结构

一、简单介绍下ViewModel有什么作用

二、通过一个类图总结ViewModel源码,总结各个关键类的作用。

三、对ViewModel的各个关键类的代码进行解读,通过注释总结每个方法的作用。

 

有错漏之处 请多多指教。

 

  • ViewModel作用

通常与LiveData一起使用,

(1)将activity, fragment里关于数据操作的逻辑抽离出来,封装到ViewModel中,所以ViewMoel 持有一个成员变量LiveData

(2)数据的操作包括什么呢? a. 从DB和缓存读取数据,显示到UI;  b. 通过网络到后台拉取数据,持久化到本地,更新DB和缓存,通知UI刷新。

(3)因此ViewModel 应该持有一个 成员变量Repository(相当于一个管理类, 命名可以命名为其他如XXXManager),做(2)的事情。 而组件activity, fragment应该持有一个成员变量ViewModel , 如图所示

 

Android架构——ViewModel源码学习总结_第1张图片

图片来源https://www.jianshu.com/p/9516a3c08a25   

demo地址:https://blog.csdn.net/xiaobaaidaba123/article/details/88667506

 

  • ViewModel 源码学习总结

 

 【架构类图】一个图总结

Android架构——ViewModel源码学习总结_第2张图片

【ViewModelProviders类】一两句话总结

1)ViewModelProviders  相当于工厂,职责是构建ViewModelProvider,所以定义了四个of方法。

2)  ViewModelProviders 持有一个静态内部类DefaultFactory,而这个DefayltFactory又继承 ViewModelProvider的静态内部类NewInstanceFactory。

3)DefaultFactory作用——通过反射构建ViewModel(真正构建ViewModel)。该DefaultFactory作为参数传递给ViewModelProvider的构造方法。

 

public class ViewModelProviders {

   /**
    **************************************************
    * 持有静态内部类DefaultFactory作为成员
    **************************************************
    */
   
    @SuppressLint("StaticFieldLeak")
    private static DefaultFactory sDefaultFactory;

   /**
    **************************************************
    * 静态内部类DefaultFactory初始化
    * 构造参数:Application
    **************************************************
    */
    private static void initializeFactoryIfNeeded(Application application) {
        if (sDefaultFactory == null) {
            sDefaultFactory = new DefaultFactory(application);
        }
    }

    /**
     **************************************************
     * of 方法 职责: 创建ViewModelProvider
     * 参数:Fragment
     **************************************************
     */
    @MainThread
    public static ViewModelProvider of(@NonNull Fragment fragment) {
        FragmentActivity activity = fragment.getActivity();
        if (activity == null) {
            throw new IllegalArgumentException(
                    "Can't create ViewModelProvider for detached fragment");
        }
        initializeFactoryIfNeeded(activity.getApplication());
        return new ViewModelProvider(ViewModelStores.of(fragment), sDefaultFactory);
    }

    /**
     **************************************************
     * of 方法 职责: 创建ViewModelProvider
     * 参数: FragmentActivity
     **************************************************
     */
    @MainThread
    public static ViewModelProvider of(@NonNull FragmentActivity activity) {
        initializeFactoryIfNeeded(activity.getApplication());
        return new ViewModelProvider(ViewModelStores.of(activity), sDefaultFactory);
    }

    /**
     **************************************************
     * of 方法 职责: 创建ViewModelProvider
     * 参数: Fragment ; Factory
     **************************************************
     */
    @MainThread
    public static ViewModelProvider of(@NonNull Fragment fragment, @NonNull Factory factory) {
        return new ViewModelProvider(ViewModelStores.of(fragment), factory);
    }

    /**
     **************************************************
     * of 方法 职责: 创建ViewModelProvider
     * 参数: FragmentActivity ; Factory
     **************************************************
     */
    @MainThread
    public static ViewModelProvider of(@NonNull FragmentActivity activity,
            @NonNull Factory factory) {
        return new ViewModelProvider(ViewModelStores.of(activity), factory);
    }

    /**
     **************************************************
     * DefaultFactory的职责:通过java反射创建ViewModel
     * DefaultFactory 继承 ViewModelProviderd的静态内部类NewInstanceFactory 
     **************************************************
     */
    @SuppressWarnings("WeakerAccess")
    public static class DefaultFactory extends ViewModelProvider.NewInstanceFactory {

        private Application mApplication;

        /**
         ***************************************************
         * DefaultFactory 构造方法
         * 参数:Application
         ***************************************************
         */
        public DefaultFactory(@NonNull Application application) {
            mApplication = application;
        }


         /**
         ***************************************************
         * java反射构建ViewModel
         * 调用ViewModel的有参构造方法
         ***************************************************
         */
        @Override
        public  T create(Class 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);
        }
    }
}

 

【ViewModelProvider】一两句话总结

1) ViewModelProvider持有两个成员变量 ViewModerStore ——存储ViewModel  和 Factory —— 创建ViewModel。

因此了解ViewModelProvider 的职责——可以把它看成一个wrapper——打包了创建ViewModel和存储ViewModel的功能。

public class ViewModelProvider {

    private static final String DEFAULT_KEY =
            "android.arch.lifecycle.ViewModelProvider.DefaultKey";

    /**
     **************************************************
     *  ViewModelProvider持有的两个成员变量
     **************************************************
     */
    private final Factory mFactory;
    private final ViewModelStore mViewModelStore;


    /**
     **************************************************
     * 实现Factory接口来创建ViewModel
     **************************************************
     */
    public interface Factory {
         T create(Class modelClass);
    }


    /**
     **************************************************
     *  ViewModelProvider构建方法
     *  参数 ViewModelStoreOwner 和 Factory
     *  ViewModelStoreOwner  是一个接口,可以返回ViewModelStore
     **************************************************
     */
    public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
        this(owner.getViewModelStore(), factory);
    }

    /**
     **************************************************
     *  ViewModelProvider构建方法
     *  参数 ViewModelStore 和 Factory
     **************************************************
     */
    public ViewModelProvider(ViewModelStore store, Factory factory) {
        mFactory = factory;
        this.mViewModelStore = store;
    }

    /**
     **************************************************
     * 先获取modelclass名字,再调用get (key, modelclass) 获取ViewModel
     **************************************************
     */
    public  T get(Class 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);
    }

    /**
     **************************************************
     * 通过key值从ViewModelStore 中获取ViewModel, 如果没有,则通过factory构建一个,再存储到
     * ViewModelStore
     **************************************************
     */
    @NonNull
    @MainThread
    public  T get(@NonNull String key, @NonNull Class 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.
            }
        }

        viewModel = mFactory.create(modelClass);
        mViewModelStore.put(key, viewModel);
        //noinspection unchecked
        return (T) viewModel;
    }

    /**
     **************************************************
     *  该工厂类  通过java反射构建ViewModel 调用无参构造方法
      **************************************************
     */
    public static class NewInstanceFactory implements Factory {

        @Override
        public  T create(Class modelClass) {
            //noinspection TryWithIdenticalCatches
            try {
                return modelClass.newInstance();
            } catch (InstantiationException e) {
                throw new RuntimeException("Cannot create an instance of " + modelClass, e);
            } catch (IllegalAccessException e) {
                throw new RuntimeException("Cannot create an instance of " + modelClass, e);
            }
        }
    }
}

 

【ViewModelStore】一两句话总结

1)ViewModelStore作用很简单——内部持有一个HashMap,存储ViewModel

public class ViewModelStore {

    /**
     **************************************************
     *  hash map存储viewModel
     **************************************************
     */
    private final HashMap mMap = new HashMap<>();

     /**
     **************************************************
     *  put方法
     **************************************************
     */

    final void put(String key, ViewModel viewModel) {
        ViewModel oldViewModel = mMap.get(key);
        if (oldViewModel != null) {
            oldViewModel.onCleared();
        }
        mMap.put(key, viewModel);
    }

     /**
     **************************************************
     *  get方法 
     **************************************************
     */

    final ViewModel get(String key) {
        return mMap.get(key);
    }

    /**
     **************************************************
     *  清除hashMap
     **************************************************
     */
    public final void clear() {
        for (ViewModel vm : mMap.values()) {
            vm.onCleared();
        }
        mMap.clear();
    }
}

【ViewModelStores】一两句话总结

1) ViewModelStores职责 ——创建ViewModelStore.

2)但是真正创建ViewModelStore 却由HolderFragment和HolderFragmentManager完成, ViewModelStores相当于一个外壳。

public class ViewModelStores {

    private ViewModelStores() {
    }

    /*
     **************************************************
     *  调用HolderFragment里的方法构建ViewmModelStore
     *  传递参数activity
     **************************************************
     */
    @MainThread
    public static ViewModelStore of(FragmentActivity activity) {
        return holderFragmentFor(activity).getViewModelStore();
    }

   /**
      **************************************************
     *  调用HolderFragment里的方法构建ViewmModelStore
     *  传递参数fragment
      **************************************************
     */
    @MainThread
    public static ViewModelStore of(Fragment fragment) {
        return holderFragmentFor(fragment).getViewModelStore();
    }
}


 

【HolderFragment】一两句话总结

1) HolderFragment 实际上就是Fragment, 它继承Framgnet同时持有一个静态内部类HolderFragmentManager。

实际上这种设计模式有点类似Builder设计模式——Android的dialog。

2) HolderFragment.holderFragmentFor方法——调用自己的静态内部类HolderFragmentManager.holderFragmentFor方法。

因此学习HolderFragment的核心就是静态内部类HolderFragmentManager的holderFragmentFor方法。

3)HolderFragmentManager.holderFragmentFor(FragmentActivity / Fragment)做的事情—— 先在内存中找HolderFragment,如果找不到,就重新构建一个,并且外部传递进来的参数FragmentActivity/Fragment注册ActivityLifecycleCallbacks或者FragmentLifecycleCallbacks来监听activity或者fragment的生命周期。

4)HolderFragment的构造方法调用setRetainInsance(true)——其所在的Activity被recreate时,HolderFragment不会被recreate,只有当所在的activity或fragment destroy 才会触发 ViewModel clear。

因此ViewModel的生命周期 如图

Android架构——ViewModel源码学习总结_第3张图片

图片来源https://developer.android.com/topic/libraries/architecture/viewmodel
public class HolderFragment extends Fragment {
    private static final String LOG_TAG = "ViewModelStores";

    /**
     *************************************************
     * 持有静态内部类HolderFragmentManager作为成员变量
     *************************************************
     */
    private static final HolderFragmentManager sHolderFragmentManager = new HolderFragmentManager();

    /**
     *************************************************
     * String 类型的TAG
     *************************************************
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static final String HOLDER_TAG =
            "android.arch.lifecycle.state.StateProviderHolderFragment";

    private SavedStateProvider mSavedStateProvider = new SavedStateProvider();

    /**
     *************************************************
     * 持有成员变量ViewModelStore, getViewModelStore()方法返回这个成员变量
     *************************************************
     */
    private ViewModelStore mViewModelStore = new ViewModelStore();
    
    /**
     *************************************************
     * setRetainInstance(true)作用:其所在的Activity被recreate时,HolderFragment不会被recreate。
     *************************************************
    */
    public HolderFragment() {
        setRetainInstance(true);
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mSavedStateProvider.restoreState(savedInstanceState);
        sHolderFragmentManager.holderFragmentCreated(this);
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mSavedStateProvider.saveState(outState);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mViewModelStore.clear();
    }

    public SavedStateProvider getSavedStateProvider() {
        return mSavedStateProvider;
    }


    /**
     * get方法返回 ViewModelStore
     */
    public ViewModelStore getViewModelStore() {
        return mViewModelStore;
    }

    /**
     *************************************************
     * 一个静态方法, 通过静态内部类HolderFragmentManager的holderFragmentFor方法返回HolderFrament——类似buulder设计模式
     *************************************************
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static HolderFragment holderFragmentFor(FragmentActivity activity) {
        return sHolderFragmentManager.holderFragmentFor(activity);
    }

    /**
     *************************************************
     * 一个静态方法, 通过静态内部类HolderFragmentManager的holderFragmentFor方法返回HolderFrament——类似buulder设计模式
    *************************************************
     */
    @RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
    public static HolderFragment holderFragmentFor(Fragment fragment) {
        return sHolderFragmentManager.holderFragmentFor(fragment);
    }


   /**
     *************************************************
     * 静态内部类HolderFragmentManager
     *************************************************
     */
    @SuppressWarnings("WeakerAccess")
    static class HolderFragmentManager {

         /***
         *************************************************
         * HashMap 建立所在的activity 与 HolderFragment 的映射关系。
         *************************************************
         */
        private Map mNotCommittedActivityHolders = new HashMap<>();
         /***
         *************************************************
         * HashMap 建立所在的fragment 与 HolderFragment 的映射关系。
         *************************************************
         */
        private Map mNotCommittedFragmentHolders = new HashMap<>();

        /***
         *************************************************
         *  ActivityLifecycleCallbacks 主要作用 监听acitity 的生命周期
         *  所在的actiivty onDestroy后 删除HashMap中相应的映射关系
         *************************************************
         */

        private ActivityLifecycleCallbacks mActivityCallbacks =
                new EmptyActivityLifecycleCallbacks() {
                    @Override
                    public void onActivityDestroyed(Activity activity) {
                        HolderFragment fragment = mNotCommittedActivityHolders.remove(activity);
                        if (fragment != null) {
                            Log.e(LOG_TAG, "Failed to save a ViewModel for " + activity);
                        }
                    }
                };

        private boolean mActivityCallbacksIsAdded = false;

        /***
         *************************************************
         *  FragmentLifecycleCallbacks   主要作用 监听 fragment 的生命周期
         *  所在的actiivty onDestroy后 删除HashMap中相应的映射关系
         *************************************************
         */

        private FragmentLifecycleCallbacks mParentDestroyedCallback =
                new FragmentLifecycleCallbacks() {
                    @Override
                    public void onFragmentDestroyed(FragmentManager fm, Fragment parentFragment) {
                        super.onFragmentDestroyed(fm, parentFragment);
                        HolderFragment fragment = mNotCommittedFragmentHolders.remove(
                                parentFragment);
                        if (fragment != null) {
                            Log.e(LOG_TAG, "Failed to save a ViewModel for " + parentFragment);
                        }
                    }
                };


        /***
         *************************************************
         * HolderFragment 被 Created 之后  需要做的逻辑
         *************************************************
         */
        void holderFragmentCreated(Fragment holderFragment) {
            Fragment parentFragment = holderFragment.getParentFragment();
            if (parentFragment != null) {
                mNotCommittedFragmentHolders.remove(parentFragment);
                parentFragment.getFragmentManager().unregisterFragmentLifecycleCallbacks(
                        mParentDestroyedCallback);
            } else {
                mNotCommittedActivityHolders.remove(holderFragment.getActivity());
            }
        }

        
        /***
         *************************************************
         * FragmentManager中查找HolderFragment
         * 与createHolderFragment()方法配对
         *************************************************
         */
        private static HolderFragment findHolderFragment(FragmentManager manager) {
            if (manager.isDestroyed()) {
                throw new IllegalStateException("Can't access ViewModels from onDestroy");
            }

            Fragment fragmentByTag = manager.findFragmentByTag(HOLDER_TAG);
            if (fragmentByTag != null && !(fragmentByTag instanceof HolderFragment)) {
                throw new IllegalStateException("Unexpected "
                        + "fragment instance was returned by HOLDER_TAG");
            }
            return (HolderFragment) fragmentByTag;
        }


        /***
         *************************************************
         * 创建HolderFragment 并且通过FragmentManager add TAG
         * 与 findHolderFragment() 方法配对
         *************************************************
         */
        private static HolderFragment createHolderFragment(FragmentManager fragmentManager) {
            HolderFragment holder = new HolderFragment();
            fragmentManager.beginTransaction().add(holder, HOLDER_TAG).commitAllowingStateLoss();
            return holder;
        }


        
        /***
         *************************************************
         * HolderFragmentManager的holderFragmentFor 被 HolderFragment.holderFragmentFor调用; 作用——查找或者重新构建一个HolderFragment返回。
         参数:FragmentActivity
         *************************************************
         */
        HolderFragment holderFragmentFor(FragmentActivity activity) {
            FragmentManager fm = activity.getSupportFragmentManager();
            HolderFragment holder = findHolderFragment(fm);
            if (holder != null) {
                return holder;
            }
            holder = mNotCommittedActivityHolders.get(activity);
            if (holder != null) {
                return holder;
            }

            if (!mActivityCallbacksIsAdded) {
                mActivityCallbacksIsAdded = true;
                activity.getApplication().registerActivityLifecycleCallbacks(mActivityCallbacks);
            }
            holder = createHolderFragment(fm);
            mNotCommittedActivityHolders.put(activity, holder);
            return holder;
        }


        /***
         *************************************************
         * HolderFragmentManager的holderFragmentFor 被 HolderFragment.holderFragmentFor调用; 作用——查找或者重新构建一个HolderFragment返回。
         参数:Fragment
         *************************************************
        */
        HolderFragment holderFragmentFor(Fragment parentFragment) {
            FragmentManager fm = parentFragment.getChildFragmentManager();
            HolderFragment holder = findHolderFragment(fm);
            if (holder != null) {
                return holder;
            }
            holder = mNotCommittedFragmentHolders.get(parentFragment);
            if (holder != null) {
                return holder;
            }

            parentFragment.getFragmentManager()
                    .registerFragmentLifecycleCallbacks(mParentDestroyedCallback, false);
            holder = createHolderFragment(fm);
            mNotCommittedFragmentHolders.put(parentFragment, holder);
            return holder;
        }
    }
}

 

你可能感兴趣的:(Android架构)