ViewModel 類旨在以注重生命週期的方式存儲和管理界面的數據,讓數據能夠在發生屏幕旋轉等配置更改後繼續保留。它還處理界面與應用其餘部分的通訊(例如,調用業務邏輯類)。界面應該可以觀察ViewModel 中的更改,一般經過LiveData 或者 DataBinding 公開此信息,它決不能擁有界面的引用。java
public abstract class ViewModel {
// Can't use ConcurrentHashMap, because it can lose values on old apis (see b/37042460)
@Nullable
private final Map<String, Object> mBagOfTags = new HashMap<>();
private volatile boolean mCleared = false;
/** * ViewModel 被清除是會調用這個方法 * 咱們能夠重寫這個方法在裏面作一些回收工做 */
@SuppressWarnings("WeakerAccess")
protected void onCleared() {
}
@MainThread
final void clear() {
mCleared = true;
if (mBagOfTags != null) {
synchronized (mBagOfTags) {
for (Object value : mBagOfTags.values()) {
// see comment for the similar call in setTagIfAbsent
closeWithRuntimeException(value);
}
}
}
onCleared();
}
@SuppressWarnings("unchecked")
<T> T setTagIfAbsent(String key, T newValue) {
T previous;
synchronized (mBagOfTags) {
previous = (T) mBagOfTags.get(key);
if (previous == null) {
mBagOfTags.put(key, newValue);
}
}
T result = previous == null ? newValue : previous;
if (mCleared) {
closeWithRuntimeException(result);
}
return result;
}
/** * Returns the tag associated with this viewmodel and the specified key. */
@SuppressWarnings({"TypeParameterUnusedInFormals", "unchecked"})
<T> T getTag(String key) {
if (mBagOfTags == null) {
return null;
}
synchronized (mBagOfTags) {
return (T) mBagOfTags.get(key);
}
}
private static void closeWithRuntimeException(Object obj) {
if (obj instanceof Closeable) {
try {
((Closeable) obj).close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
複製代碼
能夠看到 ViewModel 的源碼其實很簡單,就是維護mBagOfTags 這個HashMap和clear() 這個函數。接着咱們看下clear() 在哪裏被調用android
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() 裏面被調用了。能夠看到ViewModelStore 這個類就是管理ViewModel。而ViewModelStore 的clear()是在Activity 的構造方法中被調用api
public 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();
}
}
}
});
//省略代碼...
}
複製代碼
當Activity onDistroy 的時候且不是更改配置的狀況下就會調用 getViewModelStore().clear() 這樣ViewModel 就會被清除。 接着咱們看下是誰把ViewModel put 進來的。markdown
public class ViewModelProvider {
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);
}
@SuppressWarnings("unchecked")
@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;
}
//省略代碼...
}
複製代碼
能夠看到get方法大體就是若是存在就直接返回,若是沒有就建立有個ViewModel保存並返回。這裏用到了mViewModelStore、mFactory 兩個對象,這兩個對象ViewModelProvider 類在構造方法中實例化的,咱們接着看下它的構造方法。app
public class ViewModelProvider {
//省略代碼...
private final Factory mFactory;
private final ViewModelStore mViewModelStore;
//構造函數1
public ViewModelProvider(@NonNull ViewModelStoreOwner owner) {
this(owner.getViewModelStore(), owner instanceof HasDefaultViewModelProviderFactory
? ((HasDefaultViewModelProviderFactory) owner).getDefaultViewModelProviderFactory()
: NewInstanceFactory.getInstance());
}
public ViewModelProvider(@NonNull ViewModelStoreOwner owner, @NonNull Factory factory) {
this(owner.getViewModelStore(), factory);
}
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
mViewModelStore = store;
}
//省略代碼...
}
複製代碼
咱們一般用的都是「構造函數1」 須要傳入ViewModelStoreOwner 對象,這是一個接口類ide
@SuppressWarnings("WeakerAccess")
public interface ViewModelStoreOwner {
/** * Returns owned {@link ViewModelStore} * * @return a {@code ViewModelStore} */
@NonNull
ViewModelStore getViewModelStore();
}
複製代碼
咱們使用的時候傳入的是Activity/Fragment,因此可知 Activity/Fragment 都實現了這個接口。 能夠看到 「owner instanceof HasDefaultViewModelProviderFactory」 說明同時還可能實現了HasDefaultViewModelProviderFactory 這個接口。函數
public class ComponentActivity extends androidx.core.app.ComponentActivity implements LifecycleOwner, ViewModelStoreOwner, HasDefaultViewModelProviderFactory, SavedStateRegistryOwner, OnBackPressedDispatcherOwner {
複製代碼
果真是這樣的,這裏咱們就先看下HasDefaultViewModelProviderFactory 這個接口oop
public interface HasDefaultViewModelProviderFactory {
/** * Returns the default {@link ViewModelProvider.Factory} that should be * used when no custom {@code Factory} is provided to the * {@link ViewModelProvider} constructors. * * @return a {@code ViewModelProvider.Factory} */
@NonNull
ViewModelProvider.Factory getDefaultViewModelProviderFactory();
}
複製代碼
接這個咱們看下Activity 對ViewModelStoreOwner、HasDefaultViewModelProviderFactory 接口方法的實現this
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) {
//恢復viewModelStore
mViewModelStore = nc.viewModelStore;
}
if (mViewModelStore == null) {
mViewModelStore = new ViewModelStore();
}
}
return mViewModelStore;
}
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.");
}
if (mDefaultFactory == null) {
mDefaultFactory = new SavedStateViewModelFactory(
getApplication(),
this,
getIntent() != null ? getIntent().getExtras() : null);
}
return mDefaultFactory;
}
複製代碼
咱們先看 getViewModelStore() 正常狀況下在第一次調用時建立實例,下次調用直接獲取。NonConfigurationInstances 這個類主要做用是,在發生屏幕旋轉等配置更改會將一些須要保存的實例放在這裏面,並傳遞給下一個Activity(恢復的Activity),這樣就能保證這些實例在這種狀況下無需從新建立;好比ViewModelStorespa
getDefaultViewModelProviderFactory() 第一次調用的時候會建立一個SavedStateViewModelFactory 對象。顧名思義,就是 保存狀態的ViewModel工廠,代碼就不帶你們看了。主要邏輯就是若是不須要 SavedStateHandle 就是經過反射建立一個ViewModel 對象。須要 SavedStateHandle 的狀況你們能夠看下這篇文章 www.jianshu.com/p/731ca4282…
以上咱們從ViewModel 的源碼反向推倒知道了 ViewModel 的建立、恢復以及清除的過程。
所以咱們也知道了,爲何Activity 在發生屏幕旋轉等配置更改時ViewModel 沒有從新建立;ViewModel 的生命週期爲何要比Activity 長一點。還不知道的同窗能夠從新看一遍。