一、前言
關(guān)于Android Jetpack是什么不在贅述拗胜,不了解的同學(xué)可以看看Android架構(gòu)木木的這篇文章Android Jetpack讓Android一飛沖天梢薪。
此文章為Android Jetpack系列文章,內(nèi)容如下:
Android Jetpack之ViewModel使用及源碼分析
Android Jetpack之Lifecycle使用及源碼分析
未完待續(xù)。拼余。。亩歹。匙监。凡橱。
二、使用ViewModel意義
使用ViewModel的意義在于亭姥,當(dāng)我們在Activity中創(chuàng)建ViewModel對象時稼钩,即使Activity銷毀了,ViewModel對象還是存在的达罗,這樣就能在頁面恢復(fù)時拿到ViewModel對象中之前的數(shù)據(jù)重新渲染頁面坝撑。所以我們通常會將ViewModel和LiveData結(jié)合起來使用,LiveData在本文暫時不做介紹粮揉。
我們來看看以下兩個場景巡李。
場景一:當(dāng)用戶正在界面輸入表單時,因為某種原因?qū)е陆缑嬷亟朔鋈希脩糨斎氲男畔⑷紱]有了侨拦,需要再次輸入。當(dāng)然了有些原生控件其實已經(jīng)自己實現(xiàn)了通過onSaveInstanceState恢復(fù)數(shù)據(jù)辐宾,如果內(nèi)部沒有實現(xiàn)狱从,則需要考慮使用onSaveInstanceState,但是onSaveInstanceState通常用來恢復(fù)可以序列化的少量數(shù)據(jù)螃概。
場景二:應(yīng)用首頁有一個列表矫夯,某種原因?qū)е陆缑嬷亟耍缑婵赡芤黄瞻椎跬荨MǔN覀儠鲆恍┨幚硌得玻热缰匦抡{(diào)用接口或者加載本地緩存。
針對以上兩個場景冒窍,如果將數(shù)據(jù)保存在ViewModel中递沪,我們可以直接獲取到來重新渲染頁面。
三综液、使用方法
1款慨、首先創(chuàng)建一個ViewModel類
package com.example.viewmoel;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
public class TestViewModel extends ViewModel {
//存儲一個字符串
private MutableLiveData<String> liveData = new MutableLiveData<>();
public MutableLiveData<String> getLiveData() {
return liveData;
}
//改變字符串的值
public void setLiveData(String arg){
liveData.setValue(arg);
}
}
2、在實際要使用的界面使用
package com.example.test;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import com.example.test.databinding.ActivityMainBinding;
import com.example.viewmoel.TestViewModel;
public class MainActivity extends AppCompatActivity {
private TestViewModel viewModel;
private ActivityMainBinding viewBinding;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
viewBinding = ActivityMainBinding.inflate(LayoutInflater.from(this));
setContentView(viewBinding.getRoot());
initViewModel();
updateUI();
}
//初始化TestViewModel
private void initViewModel() {
ViewModelProvider provider = new ViewModelProvider(
this,
ViewModelProvider.AndroidViewModelFactory.getInstance(getApplication())
);
viewModel = provider.get(TestViewModel.class);
}
private void updateUI() {
//點擊按鈕改變TestViewModel中存儲的字符串的值
viewBinding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
viewModel.setLiveData("測試改變文字");
}
});
//觀察到字符串的值發(fā)生變化后更新UI
viewModel.getLiveData().observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
viewBinding.textView.setText(s);
}
});
}
}
可以發(fā)現(xiàn)代碼很簡單谬莹,大致邏輯如下:
1檩奠、創(chuàng)建一個ViewModel保存數(shù)據(jù)蕾哟,并提供相應(yīng)的改變數(shù)據(jù)的方法箱沦,這里還使用了LiveData,暫時不對其做介紹购公,可以簡單理解為一個String對象即可丛版。
2、在使用界面創(chuàng)建一個ViewModelProvider對象菩浙,用它來獲取ViewModel對象赋秀。
3拷获、點擊按鈕改變了ViewModel對象中String的值喳钟,觀察到字符串的值發(fā)生變化后更新UI屁使,這個觀察值的變化使用了LiveData在岂,暫時不對其做介紹。
四蛮寂、源碼分析
看完以上的使用介紹蔽午,大家可能會有如下問題:
1、為什么Activity銷毀了共郭,ViewModel對象還在祠丝?
2疾呻、如何保證重新創(chuàng)建Activity時除嘹,獲取到的還是原來的ViewModel對象?
3岸蜗、這個創(chuàng)建ViewModel對象的過程和Activity有關(guān)聯(lián)尉咕,會不會產(chǎn)生內(nèi)存泄漏?
4璃岳、ViewModel對象什么時機(jī)清除年缎,難道一直存在內(nèi)存?
我們帶著問題來一步步看源碼铃慷,首先分析ViewModelProvider单芜,看他的名字和使用方法,感覺他是一個內(nèi)容提供者犁柜,用來提供我們想要的ViewModel對象洲鸠,來看看構(gòu)造方法。
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
this(owner.getViewModelStore(), factory);
}
//最終調(diào)用下面方法
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
mViewModelStore = store;
}
到這里感覺ViewModelProvider好像是一個工具類馋缅,接收兩個參數(shù)扒腕,ViewModelStore好像是用來存儲ViewModel的,F(xiàn)actory好像是一個創(chuàng)建對象的工廠萤悴。另外我們使用的時候第一個參數(shù)傳遞的是this瘾腰,是不是AppCompatActivity實現(xiàn)或者繼承了ViewModelStoreOwner ?點擊AppCompatActivity一層層往上找覆履,在ComponentActivity中我們看到了如下代碼蹋盆,原來ViewModelStoreOwner是一個接口。
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
LifecycleOwner,
ViewModelStoreOwner,
SavedStateRegistryOwner,
OnBackPressedDispatcherOwner {
// Lazily recreated from NonConfigurationInstances by getViewModelStore()
private ViewModelStore mViewModelStore;
static final class NonConfigurationInstances {
Object custom;
ViewModelStore viewModelStore;
}
@Override
@Nullable
public final Object onRetainNonConfigurationInstance() {
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;
}
@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.");
}
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
}
分析上面代碼硝全,可以得出以下結(jié)論:
1栖雾、ViewModelProvider拿到的是當(dāng)前Activity的ViewModelStore。
2柳沙、當(dāng)頁面銷毀重建時岩灭,會根據(jù)onRetainNonConfigurationInstance和getLastNonConfigurationInstance來恢復(fù)獲取到原來的ViewModelStore對象,并且是從NonConfigurationInstances 這個靜態(tài)內(nèi)部類恢復(fù)的赂鲤。
3噪径、ViewModelStore是懶加載創(chuàng)建的柱恤。
再來看看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();
}
}
搜索一下clear方法在哪里調(diào)用梗顺,可以在ComponentActivity中找到下面一段代碼:
getLifecycle().addObserver(new LifecycleEventObserver() {
@Override
public void onStateChanged(@NonNull LifecycleOwner source,
@NonNull Lifecycle.Event event) {
if (event == Lifecycle.Event.ON_DESTROY) {
if (!isChangingConfigurations()) {
getViewModelStore().clear();
}
}
}
});
很明顯如果destory的時候不是配置發(fā)生變化,就要清除掉车摄。這里拋出一個問題寺谤,在Fragment中時機(jī)是如何的了?
接下來分析第二個參數(shù)AndroidViewModelFactory吮播,還是從使用入手变屁,可以看到如下代碼:
public static class AndroidViewModelFactory extends ViewModelProvider.NewInstanceFactory {
@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);
}
}
//繼承自NewInstanceFactory
public static class NewInstanceFactory implements Factory {
@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);
}
}
}
證實了我們剛剛的想法,這個Factory就是用來創(chuàng)建ViewModel的意狠,如果傳進(jìn)來的class是繼承自AndroidViewModel粟关,則通過反射傳遞一個Application類型的參數(shù)來生成對象,否則直接newInstance()生成對象环戈。這樣我們就不需要關(guān)聯(lián)Acticity來獲取上下文了闷板,所以在合適的場景可以將自己的ViewModel從AndroidViewModel繼承。
那么我們的ViewModel是在何時創(chuàng)建院塞,又是怎么取出來的了遮晚,同樣從使用入手,查看ViewModelProvider的get方法拦止,代碼如下:
private static final String DEFAULT_KEY =
"androidx.lifecycle.ViewModelProvider.DefaultKey";
@NonNull
@MainThread
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);
}
//最終調(diào)用到這個方法
@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;
}
這里其實就已經(jīng)很清楚了县遣,過程如下:
1、通過ViewModelProvider工具類從ViewModelStore中的HashMap里面獲取ViewModel创泄。
2艺玲、獲取的key為DEFAULT_KEY+ViewModel類的完整路徑名稱字符串。
3鞠抑、如果沒有就調(diào)用Factory創(chuàng)建一個饭聚,并且保存在ViewModelStore中。
至此搁拙,整個源碼分析過程結(jié)束秒梳。