ViewModel源码阅读(一)ViewModel的创建和生命周期

文章说明

用来记录ViewModel的源码阅读
阅读版本
androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0
androidx.activity:activity-ktx:1.3.0

阅读目的

为了搞清ViewModel生命周期和Activity重置原理

源代码阅读

  val model: EnglishViewModel by viewModels()

初始化ViewModel时通过kotlin的委托,委托到了viewModels()方法体中

@MainThread//声明主线程使用
//通过ComponentActivity的扩展函数置顶viewModels的使用范围在ComponentActivity
public inline fun  ComponentActivity.viewModels(
//默认入参方法体为空,方法构造用Lambda语法定义方法体为空入参返回Factory类型
    noinline factoryProducer: (() -> Factory)? = null
): Lazy {
若入参返回Factory的方法体为空,使用defaultViewModelProviderFactory方法体
    val factoryPromise = factoryProducer ?: {
        defaultViewModelProviderFactory
    }
//返回真正的委托函数
    return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
}

这个类只是去处理了一个委托方法默认参数,真正的委托函数在ViewModelLazy方法,所以ViewModelLazy方法里应该有初始化ViewModel的代码,但是我们需要先研究factoryPromise和viewModelStore两个方法入参都包含了什么
由于是ComponentActivity的扩展函数,所以defaultViewModelProviderFactory方法在ComponentActivity中,代码如下

    @NonNull
    @Override
    public ViewModelProvider.Factory getDefaultViewModelProviderFactory() {
//空异常
        if (getApplication() == null) {
            throw new IllegalStateException("Your activity is not yet attached to the "
                    + "Application instance. You can't request ViewModel before onCreate call.");
        }
//懒加载方式创建SavedStateViewModelFactory
        if (mDefaultFactory == null) {
            mDefaultFactory = new SavedStateViewModelFactory(
                    getApplication(),
                    this,
                    getIntent() != null ? getIntent().getExtras() : null);
        }
        return mDefaultFactory;
    }

通过以上代码察觉,defaultViewModelProviderFactory方法执行后得到的是一个SavedStateViewModelFactory,先不往下追,再看viewModelStore干了什么,和defaultViewModelProviderFactory同理,viewModelStore也是ComponentActivity成员方法,代码如下

  @NonNull
    @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.");
        }
//处理viewModelStore的初始化
        ensureViewModelStore();
        return mViewModelStore;
    }

    @SuppressWarnings("WeakerAccess") /* synthetic access */
    void ensureViewModelStore() {
//判空
        if (mViewModelStore == null) {
//这里通过getLastNonConfigurationInstance获取上次存储数据????横竖平切换,数据存储核心代码估计就是这个破玩意了
            NonConfigurationInstances nc =
                    (NonConfigurationInstances) getLastNonConfigurationInstance();
//以下代码就是判断缓存的东西有没有,有就拿,没有就自己创建
            if (nc != null) {
                // Restore the ViewModelStore from NonConfigurationInstances
                mViewModelStore = nc.viewModelStore;
            }
            if (mViewModelStore == null) {
                mViewModelStore = new ViewModelStore();
            }
        }
    }

最终发现viewModelStore是通过getLastNonConfigurationInstance获取的,也就是说销毁和切换操作viewModelStore是有数据存储的,配合getLastNonConfigurationInstance的方法是onRetainNonConfigurationInstance,所以可以在当前类找到以下代码

  @Override
    @Nullable
    @SuppressWarnings("deprecation")
    public final Object onRetainNonConfigurationInstance() {
        // Maintain backward compatibility.
        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;
    }

逻辑很简单,就是如果当前存在ViewModelStore就保存当前的,若果缓存存在就保存缓存的,那ViewModel的生命周期应该就是整个Activity无论切入后台还是如何屏幕翻转还是切换语言,ViewModelStore可以保存一个当前实例
那ViewModelStore是什么东西?代码如下

public class ViewModelStore {

    private final HashMap 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 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里只是一个大Map,存了String和ViewModel,至此ViewModel的生命周期一半已经和Activity挂钩了,在这里我们看到了clear方法,这个clear应该是清除ViewModel的,我们大胆猜测应该是Activity执行onDestory的时候,执行,所以回到ComponentActivity搜索onDestory。
onDestory没有搜索到,但是发现ComponentActivity实现了一大坨LifecycleOwner,所以我们搜索ON_DESTROY,果然在构造函数里看到如下代码

        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();
                    }
                }
            }
        });

通过 isChangingConfigurations 来判断是否是真实销毁,如果是真实销毁,就将ViewModelStore里的ViewModel全部清理了。
好吧看到这里,其实viewModel的生命周期已经几乎完成了,但是,创建流程还没有走完,所以回到ViewModelLazy中查看创建流程

public class ViewModelLazy (
    private val viewModelClass: KClass,
    private val storeProducer: () -> ViewModelStore,
    private val factoryProducer: () -> ViewModelProvider.Factory
) : Lazy {
    private var cached: VM? = null

    override val value: VM
        get() {
            val viewModel = cached
            return if (viewModel == null) {
                val factory = factoryProducer()
                val store = storeProducer()
//真正的创建流程,通过also做了一个缓存赋值,so why?因为内联吗?
                ViewModelProvider(store, factory).get(viewModelClass.java).also {
                    cached = it
                }
            } else {
                viewModel
            }
        }
//委托处理判断值是否已存在
    override fun isInitialized(): Boolean = cached != null
}

创建的核心流程在ViewModelProvider的get里,ViewModelProvider的构造函数就是做了store和factory的赋值
所以直奔get方法

    @NonNull
    @MainThread
    public  T get(@NonNull Class modelClass) {
//拿了一个类唯一标识
        String canonicalName = modelClass.getCanonicalName();
        if (canonicalName == null) {
            throw new IllegalArgumentException("Local and anonymous classes can not be ViewModels");
        }
  //DEFAULT_KEY= "androidx.lifecycle.ViewModelProvider.DefaultKey";
        return get(DEFAULT_KEY + ":" + canonicalName, modelClass);
    }

上段代码可以知道,get方法的key是通过DEFAULT_KEY+getCanonicalName生成的,保证了ViewModel的key唯一性。
来看get的主方法

    @NonNull
    @MainThread
    public  T get(@NonNull String key, @NonNull Class 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;
    }

逻辑也不复杂,就是判断viewModel是否为空 (通过isInstance判断这点很高明,判断了空和是否是ViewModel的子类),有值返回,没有就通过create创建。
那核心流程应该就是一开始我们看的SavedStateViewModelFactory了,回到SavedStateViewModelFactory仔细研读
SavedStateViewModelFactory extends ViewModelProvider.KeyedFactory extends OnRequeryFactory
所以上面的所有判断流程如果存在值的话应该都会执行,所以我们先看create方法

    @NonNull
    @Override
    public  T create(@NonNull String key, @NonNull Class modelClass) {
//判断是否是AndroidViewModel 
        boolean isAndroidViewModel = AndroidViewModel.class.isAssignableFrom(modelClass);

        Constructor constructor;
//如果是AndroidViewModel 获取 带有mApplication和handler参数的构造函数
        if (isAndroidViewModel && mApplication != null) {
            constructor = findMatchingConstructor(modelClass, ANDROID_VIEWMODEL_SIGNATURE);
        } else {
            constructor = findMatchingConstructor(modelClass, VIEWMODEL_SIGNATURE);
        }
        // doesn't need SavedStateHandle
//如果没有handler的构造函数,直接创建。 mFactory在构造函数中创建的,下面会看
        if (constructor == null) {
            return mFactory.create(modelClass);
        }
//这里主要负责创建SavedStateHandleController  这里就是SavedStateHandler相关逻辑了
        SavedStateHandleController controller = SavedStateHandleController.create(
                mSavedStateRegistry, mLifecycle, key, mDefaultArgs);
        try {
            T viewmodel;
//通过反射构造函数创建ViewModel
            if (isAndroidViewModel && mApplication != null) {
                viewmodel = constructor.newInstance(mApplication, controller.getHandle());
            } else {
                viewmodel = constructor.newInstance(controller.getHandle());
            }
            viewmodel.setTagIfAbsent(TAG_SAVED_STATE_HANDLE_CONTROLLER, controller);
            return viewmodel;
        } catch (IllegalAccessException e) {
            throw new RuntimeException("Failed to access " + modelClass, e);
        } catch (InstantiationException e) {
            throw new RuntimeException("A " + modelClass + " cannot be instantiated.", e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException("An exception happened in constructor of "
                    + modelClass, e.getCause());
        }
    }

看完以上代码,ViewModel的创建流程已经80%了,剩下就是mFactory直接Create出来的ViewModel和SavedStateHandler相关的逻辑了。先看简单的

    @SuppressLint("LambdaLast")
    public SavedStateViewModelFactory(@Nullable Application application,
            @NonNull SavedStateRegistryOwner owner,
            @Nullable Bundle defaultArgs) {
        mSavedStateRegistry = owner.getSavedStateRegistry();
        mLifecycle = owner.getLifecycle();
        mDefaultArgs = defaultArgs;
        mApplication = application;
        mFactory = application != null
                ? ViewModelProvider.AndroidViewModelFactory.getInstance(application)
                : ViewModelProvider.NewInstanceFactory.getInstance();
    }

在SavedStateViewModelFactory构造函数中,mFactory通过application判断是创建了AndroidViewModelFactory和NewInstanceFactory,这两个factory的create的方法只是 return modelClass.newInstance();和return modelClass.getConstructor(Application.class).newInstance(mApplication);的区别,代码如下

//NewInstanceFactory
  @SuppressWarnings("ClassNewInstance")
        @NonNull
        @Override
        public  T create(@NonNull 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);
            }
        }
//AndroidViewModelFactory
   @NonNull
        @Override
        public  T create(@NonNull 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);
        }

好了,创建流程就这么简单,至此ViewModel的生命周期和创建流程就很清晰了。先总结一下流程
创建流程
viewModels 通过扩展函数的方式,执行了ComponentActivity里的getDefaultViewModelProviderFactory和getViewModelStore,分别创建了SavedStateViewModelFactory 和ViewModelStore,并将实例委托给了ViewModelLazy类
其中ViewModelStore的生命周期通过getLastNonConfigurationInstance和onRetainNonConfigurationInstance组合方式对后台切换,屏幕翻转等做了数据缓存,并且通过ComponentActivity的构造函数用Lifecycle监听了ON_DESTROY,在actvity销毁时清除ViewModelStore中存储的所有ViewModel,完成了ViewModelStore对应的Activity生命周期,也是ViewModelStore中ViewModel的生命周期
ViewModelLazy通过继承Lazy方法,重写get()实现了viewModels的委托实例,然后用ViewModelProvider的get方法获取ViewModel
ViewModelProvider的get方法先会判断ViewModelStore中是否有缓存,然后通过SavedStateViewModelFactory在构造函数中的Factory创建ViewModel
下面是我自己画的简易代码逻辑

简易代码逻辑

最后我们遗留了一个问题,SavedStateHandleController究竟干了什么,下篇文章会继续阅读ViewModel源码阅读(二)SavedStateHandle的基本数据缓存原理

你可能感兴趣的:(ViewModel源码阅读(一)ViewModel的创建和生命周期)