Android ViewModel的使用總結(jié)
ViewModel 相關(guān)問(wèn)題是高頻面試題。主要源于它是 MVVM 架構(gòu)模式的重要組件,并且它可以在因配置更改導(dǎo)致頁(yè)面銷毀重建時(shí)依然保留 ViewModel 實(shí)例。
看看 ViewModel 的生命周期

ViewModel 只有在正常 Activity finish 時(shí)才會(huì)被清除。
問(wèn)題來(lái)了:
- 為什么Activity旋轉(zhuǎn)屏幕后ViewModel可以恢復(fù)數(shù)據(jù)
- ViewModel 的實(shí)例緩存到哪兒了
- 什么時(shí)候 ViewModel#onCleared() 會(huì)被調(diào)用
在解決這三個(gè)問(wèn)題之前,回顧下 ViewModel 的用法特性
基本使用
MainRepository
class MainRepository {
suspend fun getNameList(): List<String> {
return withContext(Dispatchers.IO) {
listOf("張三", "李四")
}
}
}
MainViewModel
class MainViewModel: ViewModel() {
private val nameList = MutableLiveData<List<String>>()
val nameListResult: LiveData<List<String>> = nameList
private val mainRepository = MainRepository()
fun getNames() {
viewModelScope.launch {
nameList.value = mainRepository.getNameList()
}
}
}
MainActivity
class MainActivity : AppCompatActivity() {
// 創(chuàng)建 ViewModel 方式 1
// 通過(guò) kotlin 委托特性創(chuàng)建 ViewModel
// 需添加依賴 implementation 'androidx.activity:activity-ktx:1.2.3'
// viewModels() 內(nèi)部也是通過(guò) 創(chuàng)建 ViewModel 方式 2 來(lái)創(chuàng)建的 ViewModel
private val mainViewModel: MainViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate (savedInstanceState)
setContentView(R.layout.activity_main)
// 創(chuàng)建 ViewModel 方式 2
val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
mainViewModel.nameListResult.observe(this, {
Log.i("MainActivity", "mainViewModel: nameListResult: $it")
Log.i("MainActivity", "MainActivity: ${this@MainActivity} mainViewModel: $mainViewModel mainViewModel.nameListResult: ${mainViewModel.nameListResult}")
})
mainViewModel.getNames()
}
}
測(cè)試步驟:打開(kāi)app -> 正??吹饺罩?/p>
18:03:02.575 : mainViewModel: nameListResult: [張三, 李四] 18:03:02.575 : com.yqy.myapplication.MainActivity@7ffa77 mainViewModel: com.yqy.myapplication.MainViewModel@29c0057 mainViewModel.nameListResult: androidx.lifecycle.MutableLiveData@ed0d744
接著測(cè)試步驟:打開(kāi)設(shè)置更換系統(tǒng)語(yǔ)言 -> 切換到當(dāng)前app所在的任務(wù) 再看日志
18:03:59.622 : mainViewModel: nameListResult: [張三, 李四] 18:03:59.622 : com.yqy.myapplication.MainActivity@49a4455 mainViewModel: com.yqy.myapplication.MainViewModel@29c0057 mainViewModel.nameListResult: androidx.lifecycle.MutableLiveData@ed0d744
神奇!MainActivity 被重建了,而 ViewModel 的實(shí)例沒(méi)有變,并且 ViewModel 對(duì)象里的 LiveData 對(duì)象實(shí)例也沒(méi)變。 這就是 ViewModel 的特性。
ViewModel 出現(xiàn)之前,Activity 可以使用 onSaveInstanceState() 方法保存,然后從 onCreate() 中的 Bundle 恢復(fù)數(shù)據(jù),但此方法僅適合可以序列化再反序列化的少量數(shù)據(jù)(IPC 對(duì) Bundle 有 1M 的限制),而不適合數(shù)量可能較大的數(shù)據(jù),如用戶信息列表或位圖。 ViewModel 的出現(xiàn)完美解決這個(gè)問(wèn)題。
我們先看看 ViewModel 怎么創(chuàng)建的: 通過(guò)上面的實(shí)例代碼,最終 ViewModel 的創(chuàng)建方法是
val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
神奇!MainActivity 被重建了,而 ViewModel 的實(shí)例沒(méi)有變,并且 ViewModel 對(duì)象里的 LiveData 對(duì)象實(shí)例也沒(méi)變。 這就是 ViewModel 的特性。
ViewModel 出現(xiàn)之前,Activity 可以使用 onSaveInstanceState() 方法保存,然后從 onCreate() 中的 Bundle 恢復(fù)數(shù)據(jù),但此方法僅適合可以序列化再反序列化的少量數(shù)據(jù)(IPC 對(duì) Bundle 有 1M 的限制),而不適合數(shù)量可能較大的數(shù)據(jù),如用戶信息列表或位圖。 ViewModel 的出現(xiàn)完美解決這個(gè)問(wèn)題。
我們先看看 ViewModel 怎么創(chuàng)建的: 通過(guò)上面的實(shí)例代碼,最終 ViewModel 的創(chuàng)建方法是
val mainViewModel = ViewModelProvider(this).get(MainViewModel::class.java)
創(chuàng)建 ViewModelProvider 對(duì)象并傳入了 this 參數(shù),然后通過(guò) ViewModelProvider#get 方法,傳入 MainViewModel 的 class 類型,然后拿到了 mainViewModel 實(shí)例。
ViewModelProvider 的構(gòu)造方法
public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
// 獲取 owner 對(duì)象的 ViewModelStore 對(duì)象
this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
: NewInstanceFactory.getInstance());
}
ViewModelProvider 構(gòu)造方法的參數(shù)類型是 ViewModelStoreOwner ?ViewModelStoreOwner 是什么?我們明明傳入的 MainActivity 對(duì)象呀! 看看 MainActivity 的父類們發(fā)現(xiàn)
public class ComponentActivity extends androidx.core.app.ComponentActivity implements
...
// 實(shí)現(xiàn)了 ViewModelStoreOwner 接口
ViewModelStoreOwner,
...{
private ViewModelStore mViewModelStore;
// 重寫了 ViewModelStoreOwner 接口的唯一的方法 getViewModelStore()
@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.");
}
ensureViewModelStore();
return mViewModelStore;
}
ComponentActivity 類實(shí)現(xiàn)了 ViewModelStoreOwner 接口。 奧 ~~ 剛剛的問(wèn)題解決了。
再看看剛剛的 ViewModelProvider 構(gòu)造方法里調(diào)用了 this(ViewModelStore, Factory),將 ComponentActivity#getViewModelStore 返回的 ViewModelStore 實(shí)例傳了進(jìn)去,并緩存到 ViewModelProvider 中
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
// 緩存 ViewModelStore 對(duì)象
mViewModelStore = store;
}
接著看 ViewModelProvider#get 方法做了什么
@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);
}
獲取 ViewModel 的 CanonicalName , 調(diào)用了另一個(gè) get 方法
@MainThread
public <T extends ViewModel> T get(@NonNull String key, @NonNull Class<T> modelClass) {
// 從 mViewModelStore 緩存中嘗試獲取
ViewModel viewModel = mViewModelStore.get(key);
// 命中緩存
if (modelClass.isInstance(viewModel)) {
if (mFactory instanceof OnRequeryFactory) {
((OnRequeryFactory) mFactory).onRequery(viewModel);
}
// 返回緩存的 ViewModel 對(duì)象
return (T) viewModel;
} else {
//noinspection StatementWithEmptyBody
if (viewModel != null) {
// TODO: log a warning.
}
}
// 使用工廠模式創(chuàng)建 ViewModel 實(shí)例
if (mFactory instanceof KeyedFactory) {
viewModel = ((KeyedFactory) mFactory).create(key, modelClass);
} else {
viewModel = mFactory.create(modelClass);
}
// 將創(chuàng)建的 ViewModel 實(shí)例放進(jìn) mViewModelStore 緩存中
mViewModelStore.put(key, viewModel);
// 返回新創(chuàng)建的 ViewModel 實(shí)例
return (T) viewModel;
}
mViewModelStore 是啥?通過(guò) ViewModelProvider 的構(gòu)造方法知道 mViewModelStore 其實(shí)是我們 Activity 里的 mViewModelStore 對(duì)象,它在 ComponentActivity 中被聲明。 看到了 put 方法,不難猜它內(nèi)部用了 Map 結(jié)構(gòu)。
public class ViewModelStore {
// 果不其然,內(nèi)部有一個(gè) HashMap
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();
}
}
// 通過(guò) key 獲取 ViewModel 對(duì)象
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();
}
}
到這兒正常情況下 ViewModel 的創(chuàng)建流程看完了,似乎沒(méi)有解決任何問(wèn)題~ 簡(jiǎn)單總結(jié):ViewModel 對(duì)象存在了 ComponentActivity 的 mViewModelStore 對(duì)象中。 第二個(gè)問(wèn)題解決了:ViewModel 的實(shí)例緩存到哪兒了
轉(zhuǎn)換思路 mViewModelStore 出現(xiàn)頻率這么高,何不看看它是什么時(shí)候被創(chuàng)建的呢?
記不記得剛才看 ViewModelProvider 的構(gòu)造方法時(shí) ,獲取 ViewModelStore 對(duì)象時(shí),實(shí)際調(diào)用了 MainActivity#getViewModelStore() ,而 getViewModelStore() 實(shí)現(xiàn)在 MainActivity 的父類 ComponentActivity 中。
// ComponentActivity#getViewModelStore()
@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.");
}
ensureViewModelStore();
return mViewModelStore;
}
在返回 mViewModelStore 對(duì)象之前調(diào)用了 ensureViewModelStore()
void ensureViewModelStore() {
if (mViewModelStore == null) {
NonConfigurationInstances nc =
(NonConfigurationInstances) getLastNonConfigurationInstance();
if (nc != null) {
// Restore the ViewModelStore from NonConfigurationInstances
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
}
當(dāng) mViewModelStore == null 調(diào)用了 getLastNonConfigurationInstance() 獲取 NonConfigurationInstances 對(duì)象 nc,當(dāng) nc != null 時(shí)將 mViewModelStore 賦值為 nc.viewModelStore,最終 viewModelStore == null 時(shí),才會(huì)創(chuàng)建 ViewModelStore 實(shí)例。
不難發(fā)現(xiàn),之前創(chuàng)建的 viewModelStore 對(duì)象被緩存在 NonConfigurationInstances 中
// 它是 ComponentActivity 的靜態(tài)內(nèi)部類
static final class NonConfigurationInstances {
Object custom;
// 果然在這兒
ViewModelStore viewModelStore;
}
當(dāng) mViewModelStore == null 調(diào)用了 getLastNonConfigurationInstance() 獲取 NonConfigurationInstances 對(duì)象 nc,當(dāng) nc != null 時(shí)將 mViewModelStore 賦值為 nc.viewModelStore,最終 viewModelStore == null 時(shí),才會(huì)創(chuàng)建 ViewModelStore 實(shí)例。
不難發(fā)現(xiàn),之前創(chuàng)建的 viewModelStore 對(duì)象被緩存在 NonConfigurationInstances 中
// 它是 ComponentActivity 的靜態(tài)內(nèi)部類
static final class NonConfigurationInstances {
Object custom;
// 果然在這兒
ViewModelStore viewModelStore;
}
NonConfigurationInstances 對(duì)象通過(guò) getLastNonConfigurationInstance() 來(lái)獲取的
// Activity#getLastNonConfigurationInstance
/**
* Retrieve the non-configuration instance data that was previously
* returned by {@link #onRetainNonConfigurationInstance()}. This will
* be available from the initial {@link #onCreate} and
* {@link #onStart} calls to the new instance, allowing you to extract
* any useful dynamic state from the previous instance.
*
* <p>Note that the data you retrieve here should <em>only</em> be used
* as an optimization for handling configuration changes. You should always
* be able to handle getting a null pointer back, and an activity must
* still be able to restore itself to its previous state (through the
* normal {@link #onSaveInstanceState(Bundle)} mechanism) even if this
* function returns null.
*
* <p><strong>Note:</strong> For most cases you should use the {@link Fragment} API
* {@link Fragment#setRetainInstance(boolean)} instead; this is also
* available on older platforms through the Android support libraries.
*
* @return the object previously returned by {@link #onRetainNonConfigurationInstance()}
*/
@Nullable
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
好長(zhǎng)一段注釋,大概意思有幾點(diǎn):
- onRetainNonConfigurationInstance 方法和 getLastNonConfigurationInstance 是成對(duì)出現(xiàn)的,跟 onSaveInstanceState 機(jī)制類似,只不過(guò)它是僅用作處理配置更改的優(yōu)化。
- 返回的是 onRetainNonConfigurationInstance 返回的對(duì)象
onRetainNonConfigurationInstance 和 getLastNonConfigurationInstance 的調(diào)用時(shí)機(jī)在本篇文章不做贅述,后續(xù)文章會(huì)進(jìn)行解釋。
看看 onRetainNonConfigurationInstance 方法
/**
* 保留所有適當(dāng)?shù)姆桥渲脿顟B(tài)
*/
@Override
@Nullable
@SuppressWarnings("deprecation")
public final Object onRetainNonConfigurationInstance() {
// Maintain backward compatibility.
Object custom = onRetainCustomNonConfigurationInstance();
ViewModelStore viewModelStore = mViewModelStore;
// 若 viewModelStore 為空,則嘗試從 getLastNonConfigurationInstance() 中獲取
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;
}
}
// 依然為空,說(shuō)明沒(méi)有需要緩存的,則返回 null
if (viewModelStore == null && custom == null) {
return null;
}
// 創(chuàng)建 NonConfigurationInstances 對(duì)象,并賦值 viewModelStore
NonConfigurationInstances nci = new NonConfigurationInstances();
nci.custom = custom;
nci.viewModelStore = viewModelStore;
return nci;
}
到這兒我們大概明白了,Activity 在因配置更改而銷毀重建過(guò)程中會(huì)先調(diào)用 onRetainNonConfigurationInstance 保存 viewModelStore 實(shí)例。 在重建后可以通過(guò) getLastNonConfigurationInstance 方法獲取之前的 viewModelStore 實(shí)例。
現(xiàn)在解決了第一個(gè)問(wèn)題:為什么Activity旋轉(zhuǎn)屏幕后ViewModel可以恢復(fù)數(shù)據(jù)
再看第三個(gè)問(wèn)題:什么時(shí)候 ViewModel#onCleared() 會(huì)被調(diào)用
public abstract class ViewModel {
protected void onCleared() {
}
@MainThread
final void clear() {
mCleared = true;
// Since clear() is final, this method is still called on mock objects
// and in those cases, mBagOfTags is null. It'll always be empty though
// because setTagIfAbsent and getTag are not final so we can skip
// clearing it
if (mBagOfTags != null) {
synchronized (mBagOfTags) {
for (Object value : mBagOfTags.values()) {
// see comment for the similar call in setTagIfAbsent
closeWithRuntimeException(value);
}
}
}
onCleared();
}
}
onCleared() 方法被 clear() 調(diào)用了。 剛才看 ViewModelStore 源碼時(shí)好像是調(diào)用了 clear() ,回顧一下:
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();
}
}
onCleared() 方法被 clear() 調(diào)用了。 剛才看 ViewModelStore 源碼時(shí)好像是調(diào)用了 clear() ,回顧一下:
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 的 clear() 中,遍歷 mMap 并調(diào)用 ViewModel 對(duì)象的 clear() , 再看 ViewModelStore 的 clear() 什么時(shí)候被調(diào)用的:
// ComponentActivity 的構(gòu)造方法
public ComponentActivity() {
...
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();
}
}
}
});
...
}
觀察當(dāng)前 activity 生命周期,當(dāng) Lifecycle.Event == Lifecycle.Event.ON_DESTROY,并且 isChangingConfigurations() 返回 false 時(shí)才會(huì)調(diào)用 ViewModelStore#clear 。
// Activity#isChangingConfigurations()
/**
* Check to see whether this activity is in the process of being destroyed in order to be
* recreated with a new configuration. This is often used in
* {@link #onStop} to determine whether the state needs to be cleaned up or will be passed
* on to the next instance of the activity via {@link #onRetainNonConfigurationInstance()}.
*
* @return If the activity is being torn down in order to be recreated with a new configuration,
* returns true; else returns false.
*/
public boolean isChangingConfigurations() {
return mChangingConfigurations;
}
isChangingConfigurations 用來(lái)檢測(cè)當(dāng)前的 Activity 是否因?yàn)?Configuration 的改變被銷毀了, 配置改變返回 true,非配置改變返回 false。
總結(jié),在 activity 銷毀時(shí),判斷如果是非配置改變導(dǎo)致的銷毀, getViewModelStore().clear() 才會(huì)被調(diào)用。
第三個(gè)問(wèn)題:什么時(shí)候 ViewModel#onCleared() 會(huì)被調(diào)用 解決!
以上就是Android ViewModel的使用總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于Android ViewModel的使用的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Android自定義控件實(shí)現(xiàn)簡(jiǎn)單的輪播圖控件
這篇文章主要介紹了Android自定義控件實(shí)現(xiàn)簡(jiǎn)單的輪播圖控件的相關(guān)資料,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-04-04
Android判斷現(xiàn)在所處界面是否為home主桌面的方法
這篇文章主要介紹了Android判斷現(xiàn)在所處界面是否為home主桌面的方法,涉及Android界面判斷的相關(guān)技巧,需要的朋友可以參考下2015-05-05
Android開(kāi)發(fā)筆記之: 數(shù)據(jù)存儲(chǔ)方式詳解
本篇文章是對(duì)Android中數(shù)據(jù)存儲(chǔ)方式進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-05-05
Android實(shí)現(xiàn)多段顏色進(jìn)度條效果
這篇文章主要為大家詳細(xì)介紹了Android實(shí)現(xiàn)多段顏色進(jìn)度條效果,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-01-01
RecyclerView焦點(diǎn)跳轉(zhuǎn)BUG優(yōu)化的方法
這篇文章主要介紹了RecyclerView焦點(diǎn)跳轉(zhuǎn)BUG優(yōu)化的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-04-04
Android.mk文件中添加第三方j(luò)ar文件的方法
這篇文章主要介紹了Android.mk文件中添加第三方j(luò)ar文件及引用第三方j(luò)ar包的方法,需要的朋友可以參考下2018-01-01
Android仿新浪微博發(fā)布微博界面設(shè)計(jì)(5)
這篇文章主要為大家詳細(xì)介紹了Android仿新浪微博發(fā)布微博界面設(shè)計(jì)方案,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-11-11
簡(jiǎn)單掌握Android Widget桌面小部件的創(chuàng)建步驟
這篇文章主要介紹了簡(jiǎn)單掌握Android Widget桌面小部件的創(chuàng)建步驟,Widget一般采用web前端技術(shù)進(jìn)行開(kāi)發(fā),需要的朋友可以參考下2016-03-03
解決webview調(diào)用goBack()返回上一頁(yè)自動(dòng)刷新閃白的情況
本文主要介紹了解決webview調(diào)用goBack()返回上一頁(yè)自動(dòng)刷新閃白的情況。具有很好的參考價(jià)值。下面跟著小編一起來(lái)看下吧2017-03-03

