文章說明
用來記錄ViewModel的源碼閱讀
閱讀版本
androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.0
androidx.activity:activity-ktx:1.3.0
閱讀目的
為了搞清ViewModel生命周期和Activity重置原理
源代碼閱讀
val model: EnglishViewModel by viewModels()
初始化ViewModel時(shí)通過kotlin的委托,委托到了viewModels()方法體中
@MainThread//聲明主線程使用
//通過ComponentActivity的擴(kuò)展函數(shù)置頂viewModels的使用范圍在ComponentActivity
public inline fun <reified VM : ViewModel> ComponentActivity.viewModels(
//默認(rèn)入?yún)⒎椒w為空,方法構(gòu)造用Lambda語法定義方法體為空入?yún)⒎祷谾actory類型
noinline factoryProducer: (() -> Factory)? = null
): Lazy<VM> {
若入?yún)⒎祷谾actory的方法體為空碗殷,使用defaultViewModelProviderFactory方法體
val factoryPromise = factoryProducer ?: {
defaultViewModelProviderFactory
}
//返回真正的委托函數(shù)
return ViewModelLazy(VM::class, { viewModelStore }, factoryPromise)
}
這個(gè)類只是去處理了一個(gè)委托方法默認(rèn)參數(shù)衙耕,真正的委托函數(shù)在ViewModelLazy方法,所以ViewModelLazy方法里應(yīng)該有初始化ViewModel的代碼疏遏,但是我們需要先研究factoryPromise和viewModelStore兩個(gè)方法入?yún)⒍及耸裁?br> 由于是ComponentActivity的擴(kuò)展函數(shù),所以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.");
}
//懶加載方式創(chuàng)建SavedStateViewModelFactory
if (mDefaultFactory == null) {
mDefaultFactory = new SavedStateViewModelFactory(
getApplication(),
this,
getIntent() != null ? getIntent().getExtras() : null);
}
return mDefaultFactory;
}
通過以上代碼察覺脾拆,defaultViewModelProviderFactory方法執(zhí)行后得到的是一個(gè)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獲取上次存儲(chǔ)數(shù)據(jù)渠驼?蜈块??迷扇?橫豎平切換百揭,數(shù)據(jù)存儲(chǔ)核心代碼估計(jì)就是這個(gè)破玩意了
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
//以下代碼就是判斷緩存的東西有沒有,有就拿蜓席,沒有就自己創(chuàng)建
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
}
最終發(fā)現(xiàn)viewModelStore是通過getLastNonConfigurationInstance獲取的器一,也就是說銷毀和切換操作viewModelStore是有數(shù)據(jù)存儲(chǔ)的,配合getLastNonConfigurationInstance的方法是onRetainNonConfigurationInstance瓮床,所以可以在當(dāng)前類找到以下代碼
@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;
}
邏輯很簡單盹舞,就是如果當(dāng)前存在ViewModelStore就保存當(dāng)前的,若果緩存存在就保存緩存的隘庄,那ViewModel的生命周期應(yīng)該就是整個(gè)Activity無論切入后臺還是如何屏幕翻轉(zhuǎn)還是切換語言踢步,ViewModelStore可以保存一個(gè)當(dāng)前實(shí)例
那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里只是一個(gè)大Map获印,存了String和ViewModel,至此ViewModel的生命周期一半已經(jīng)和Activity掛鉤了街州,在這里我們看到了clear方法兼丰,這個(gè)clear應(yīng)該是清除ViewModel的,我們大膽猜測應(yīng)該是Activity執(zhí)行onDestory的時(shí)候唆缴,執(zhí)行鳍征,所以回到ComponentActivity搜索onDestory。
onDestory沒有搜索到面徽,但是發(fā)現(xiàn)ComponentActivity實(shí)現(xiàn)了一大坨LifecycleOwner艳丛,所以我們搜索ON_DESTROY,果然在構(gòu)造函數(shù)里看到如下代碼
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 來判斷是否是真實(shí)銷毀,如果是真實(shí)銷毀趟紊,就將ViewModelStore里的ViewModel全部清理了氮双。
好吧看到這里,其實(shí)viewModel的生命周期已經(jīng)幾乎完成了霎匈,但是戴差,創(chuàng)建流程還沒有走完,所以回到ViewModelLazy中查看創(chuàng)建流程
public class ViewModelLazy<VM : ViewModel> (
private val viewModelClass: KClass<VM>,
private val storeProducer: () -> ViewModelStore,
private val factoryProducer: () -> ViewModelProvider.Factory
) : Lazy<VM> {
private var cached: VM? = null
override val value: VM
get() {
val viewModel = cached
return if (viewModel == null) {
val factory = factoryProducer()
val store = storeProducer()
//真正的創(chuàng)建流程铛嘱,通過also做了一個(gè)緩存賦值暖释,so why?因?yàn)閮?nèi)聯(lián)嗎袭厂?
ViewModelProvider(store, factory).get(viewModelClass.java).also {
cached = it
}
} else {
viewModel
}
}
//委托處理判斷值是否已存在
override fun isInitialized(): Boolean = cached != null
}
創(chuàng)建的核心流程在ViewModelProvider的get里,ViewModelProvider的構(gòu)造函數(shù)就是做了store和factory的賦值
所以直奔get方法
@NonNull
@MainThread
public <T extends ViewModel> T get(@NonNull Class<T> modelClass) {
//拿了一個(gè)類唯一標(biāo)識
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 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;
}
邏輯也不復(fù)雜谐丢,就是判斷viewModel是否為空 (通過isInstance判斷這點(diǎn)很高明,判斷了空和是否是ViewModel的子類)蚓让,有值返回乾忱,沒有就通過create創(chuàng)建。
那核心流程應(yīng)該就是一開始我們看的SavedStateViewModelFactory了历极,回到SavedStateViewModelFactory仔細(xì)研讀
SavedStateViewModelFactory extends ViewModelProvider.KeyedFactory extends OnRequeryFactory
所以上面的所有判斷流程如果存在值的話應(yīng)該都會(huì)執(zhí)行窄瘟,所以我們先看create方法
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull String key, @NonNull Class<T> modelClass) {
//判斷是否是AndroidViewModel
boolean isAndroidViewModel = AndroidViewModel.class.isAssignableFrom(modelClass);
Constructor<T> constructor;
//如果是AndroidViewModel 獲取 帶有mApplication和handler參數(shù)的構(gòu)造函數(shù)
if (isAndroidViewModel && mApplication != null) {
constructor = findMatchingConstructor(modelClass, ANDROID_VIEWMODEL_SIGNATURE);
} else {
constructor = findMatchingConstructor(modelClass, VIEWMODEL_SIGNATURE);
}
// doesn't need SavedStateHandle
//如果沒有handler的構(gòu)造函數(shù),直接創(chuàng)建趟卸。 mFactory在構(gòu)造函數(shù)中創(chuàng)建的蹄葱,下面會(huì)看
if (constructor == null) {
return mFactory.create(modelClass);
}
//這里主要負(fù)責(zé)創(chuàng)建SavedStateHandleController 這里就是SavedStateHandler相關(guān)邏輯了
SavedStateHandleController controller = SavedStateHandleController.create(
mSavedStateRegistry, mLifecycle, key, mDefaultArgs);
try {
T viewmodel;
//通過反射構(gòu)造函數(shù)創(chuàng)建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的創(chuàng)建流程已經(jīng)80%了锄列,剩下就是mFactory直接Create出來的ViewModel和SavedStateHandler相關(guān)的邏輯了图云。先看簡單的
@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構(gòu)造函數(shù)中,mFactory通過application判斷是創(chuàng)建了AndroidViewModelFactory和NewInstanceFactory邻邮,這兩個(gè)factory的create的方法只是 return modelClass.newInstance();和return modelClass.getConstructor(Application.class).newInstance(mApplication);的區(qū)別竣况,代碼如下
//NewInstanceFactory
@SuppressWarnings("ClassNewInstance")
@NonNull
@Override
public <T extends ViewModel> T create(@NonNull Class<T> 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 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);
}
好了,創(chuàng)建流程就這么簡單筒严,至此ViewModel的生命周期和創(chuàng)建流程就很清晰了丹泉。先總結(jié)一下流程
創(chuàng)建流程
viewModels 通過擴(kuò)展函數(shù)的方式,執(zhí)行了ComponentActivity里的getDefaultViewModelProviderFactory和getViewModelStore鸭蛙,分別創(chuàng)建了SavedStateViewModelFactory 和ViewModelStore摹恨,并將實(shí)例委托給了ViewModelLazy類
其中ViewModelStore的生命周期通過getLastNonConfigurationInstance和onRetainNonConfigurationInstance組合方式對后臺切換,屏幕翻轉(zhuǎn)等做了數(shù)據(jù)緩存娶视,并且通過ComponentActivity的構(gòu)造函數(shù)用Lifecycle監(jiān)聽了ON_DESTROY晒哄,在actvity銷毀時(shí)清除ViewModelStore中存儲(chǔ)的所有ViewModel,完成了ViewModelStore對應(yīng)的Activity生命周期歇万,也是ViewModelStore中ViewModel的生命周期
ViewModelLazy通過繼承Lazy方法揩晴,重寫get()實(shí)現(xiàn)了viewModels的委托實(shí)例,然后用ViewModelProvider的get方法獲取ViewModel
ViewModelProvider的get方法先會(huì)判斷ViewModelStore中是否有緩存贪磺,然后通過SavedStateViewModelFactory在構(gòu)造函數(shù)中的Factory創(chuàng)建ViewModel
下面是我自己畫的簡易代碼邏輯
最后我們遺留了一個(gè)問題硫兰,SavedStateHandleController究竟干了什么,下篇文章會(huì)繼續(xù)閱讀ViewModel源碼閱讀(二)SavedStateHandle的基本數(shù)據(jù)緩存原理