Jetpack的ViewModel與LiveData
- 2022 年 2 月 17 日
- 筆記
本文基於SDK 29
一、ViewModel與LiveData的作用:
1、viewModel:
數據共享,屏幕旋轉不丟失數據,並且在Activity與Fragment之間共享數據。
2、LiveData:
感知生命周期並且通知觀察者刷新,防止內存泄漏。
二、用法
三、原理:
1、ViewModel:
ViewModelProviders.of(this).get(MyViewModel::class.java)
我們通過這個方法來構造ViewModel。
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity) {
return of(activity, null);
}
/**
* Creates a {@link ViewModelProvider}, which retains ViewModels while a scope of given Activity
* is alive. More detailed explanation is in {@link ViewModel}.
* <p>
* It uses the given {@link Factory} to instantiate new ViewModels.
*
* @param activity an activity, in whose scope ViewModels should be retained
* @param factory a {@code Factory} to instantiate new ViewModels
* @return a ViewModelProvider instance
*/
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
Application application = checkApplication(activity);
if (factory == null) {
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
return new ViewModelProvider(activity.getViewModelStore(), factory);
}
從源碼中可以看出,ViewModelProviders.of(this)獲取了一個ViewModelProvider 對象,而該對象中持有一個ViewModelProvider.AndroidViewModelFactory(因為我們傳進入的是null)
和activity.getViewModelStore()。
private final Factory mFactory;
private final ViewModelStore mViewModelStore;
public ViewModelProvider(@NonNull ViewModelStore store, @NonNull Factory factory) {
mFactory = factory;
this.mViewModelStore = store;
}
我們再來看看ViewModelStore這個類,從名字中已經可以看出它的用途,那便是存儲ViewModel。
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);
}
/**
* Clears internal storage and notifies ViewModels that they are no longer used.
*/
public final void clear() {
for (ViewModel vm : mMap.values()) {
vm.onCleared();
}
mMap.clear();
}
}
我們的ViewModel便是存儲在上面的HashMap中。
接下來我們再來看ViewModelProviders.of(this).get(MyViewModel::class.java)的get方法:
@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);
}
@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.
}
}
viewModel = mFactory.create(modelClass);
mViewModelStore.put(key, viewModel);
//noinspection unchecked
return (T) viewModel;
}
可以看出,所以會去存儲ViewModel的ViewModelStore中拿,發現已經有了便直接返回,如果沒有的話,那邊使用mFactory工廠進行構建,然後再放進ViewModelStore中。
從之前的分析可以看出,這裡的mFactory便是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);
}
其實該工廠也只是直接實例出該類而已。
此時我們便已經拿到了ViewModel。
可是它是怎麼做到數據共享的呢,想做到數據共享,按理說它應該只有一個實例對象,我們且看。
@NonNull
@MainThread
public static ViewModelProvider of(@NonNull FragmentActivity activity,
@Nullable Factory factory) {
Application application = checkApplication(activity);
if (factory == null) {
factory = ViewModelProvider.AndroidViewModelFactory.getInstance(application);
}
return new ViewModelProvider(activity.getViewModelStore(), factory);
}
在獲取ViewModelProvider的時候傳進去了activity.getViewModelStore(),那我們看一下activity.getViewModelStore()是怎麼獲取ViewModelStore的。
@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;
}
關鍵的代碼在於這一句:NonConfigurationInstances nc = (NonConfigurationInstances) getLastNonConfigurationInstance();
static final class NonConfigurationInstances {
Object activity;
HashMap<String, Object> children;
FragmentManagerNonConfig fragments;
ArrayMap<String, LoaderManager> loaders;
VoiceInteractor voiceInteractor;
}
/* package */ NonConfigurationInstances mLastNonConfigurationInstances;
@Nullable
public Object getLastNonConfigurationInstance() {
return mLastNonConfigurationInstances != null
? mLastNonConfigurationInstances.activity : null;
}
將mLastNonConfigurationInstances.activity強轉成FragmentActivity中的一個類:NonConfigurationInstances,然後獲取ViewModelStore
static final class NonConfigurationInstances {
Object custom;
ViewModelStore viewModelStore;
FragmentManagerNonConfig fragments;
}
NonConfigurationInstances是個靜態類,所以裏面的ViewModelStore 也是唯一的,因此ViewModelStore 能做到數據共享。
2、LivaData
我們先看這個語句:
viewModel?.livaData?.observe(this, Observer<Int> { integer -> Log.d("MainActivity", integer!!.toString()) })
從這個語句往源碼裏面探究:
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
assertMainThread("observe");
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
LifecycleBoundObserver wrapper = new LifecycleBoundObserver(owner, observer);
ObserverWrapper existing = mObservers.putIfAbsent(observer, wrapper);
if (existing != null && !existing.isAttachedTo(owner)) {
throw new IllegalArgumentException("Cannot add the same observer"
+ " with different lifecycles");
}
if (existing != null) {
return;
}
owner.getLifecycle().addObserver(wrapper);
}
如果這個activity處於銷毀狀態,那麼便不會添加該觀察者,否則,構造一個LifecycleBoundObserver對象,放進mObservers裏面,mObservers即為:
private SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers =
new SafeIterableMap<>();
然後將LifecycleBoundObserver對象放進LifecycleRegistry裏面。
LifecycleBoundObserver裏面持有的對象如下:
當我們給LiveData設置值的時候:livaData.value = i
public class MutableLiveData<T> extends LiveData<T> {
@Override
public void postValue(T value) {
super.postValue(value);
}
@Override
public void setValue(T value) {
super.setValue(value);
}
}
裏面還有個postValue方法:
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}
postValue最終也會調用到主線程。postValue可以在子線程調用,而setValue必須在主線程調用,否則會拋出異常。
我們看setValue方法:
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
void dispatchingValue(@Nullable ObserverWrapper initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if (initiator != null) {
considerNotify(initiator);
initiator = null;
} else {
for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
這裡我們傳進來的initiator為null,所以我們主要看:
for (Iterator<Map.Entry<Observer<? super T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
這裡的mObservers即為:
private SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers =
new SafeIterableMap<>();
裏面存放着我們之前放進去的LifecycleBoundObserver對象。
iterator.next().getValue()獲取的便是LifecycleBoundObserver對象。
private void considerNotify(ObserverWrapper observer) {
if (!observer.mActive) {
return;
}
// Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet.
//
// we still first check observer.active to keep it as the entrance for events. So even if
// the observer moved to an active state, if we've not received that event, we better not
// notify for a more predictable notification order.
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
//noinspection unchecked
observer.mObserver.onChanged((T) mData);
}
檢測當前生命周期,至少是處於start。
@Override
boolean shouldBeActive() {
return mOwner.getLifecycle().getCurrentState().isAtLeast(STARTED);
}
然後執行observer.mObserver.onChanged((T) mData);回調出去。
observer.mObserver便是我們傳進去的觀察者:
Observer<Int> { integer -> Log.d(“MainActivity”, integer!!.toString()) }
由以上也可以看出:我們是可以註冊多個觀察者的,所以要注意在一個Activity中只能夠註冊一次,否則會發生多個回調。
那麼有個疑問,我們這樣已經實現了,那問什麼在liveData?.observe方法裏面,不但將LifecycleBoundObserver放進LiveData的SafeIterableMap裏面,還要將其放入LifecycleRegistry
裏面。owner.getLifecycle()獲取到的便是LifecycleRegistry
這是為了在相關的生命周期內做相關的操作,根據上一篇文章,我們可以知道,當activity的生命周期發生改變的時候,會獲取添加進LifecycleRegistry的觀察者,然後對每個觀察者進行回調處理。
而在這裡便會回調LifecycleBoundObserver的onStateChanged方法。
@Override public void onStateChanged(@NonNull LifecycleOwner source, @NonNull Lifecycle.Event event) { if (mOwner.getLifecycle().getCurrentState() == DESTROYED) { removeObserver(mObserver); return; } activeStateChanged(shouldBeActive()); }
判斷如果當前處於DESTROYED狀態,那麼便將我們添加進入的觀察者移除。
否則會調用activeStateChanged(shouldBeActive())方法。
如果當前的活躍狀態與上一次一樣,那麼就直接返回。
否則如果變為活躍的狀態,那麼會調用dispatchingValue(this);
這裡要注意,我們之前調用LiveData的setValue的時候,走的的2,但是現在走的是1,因為這次傳進來的參數不為空。
private void considerNotify(ObserverWrapper observer) { if (!observer.mActive) { return; } // Check latest state b4 dispatch. Maybe it changed state but we didn't get the event yet. // // we still first check observer.active to keep it as the entrance for events. So even if // the observer moved to an active state, if we've not received that event, we better not // notify for a more predictable notification order. if (!observer.shouldBeActive()) { observer.activeStateChanged(false); return; } if (observer.mLastVersion >= mVersion) { return; } observer.mLastVersion = mVersion; observer.mObserver.onChanged((T) mData); }
然後進入considerNotify這個方法,裏面有一個判斷十分重要:
if (observer.mLastVersion >= mVersion) { return; }
這個判斷是做什麼用的呢?mVersion是什麼時候被賦值的,這時候就要我們回過去頭去看LiveData的setValue方法:
每調用一次,那麼這個mVersion就會自加一。
所以這個判斷便保證了,必須是刷新了LiveData裏面的data值,才能夠回調觀察者事件:observer.mObserver.onChanged((T) mData);
如果生命周期變化的時候,LiveData裏面的data值沒有刷新,就不能回調出去。所以如果刷新LiveData裏面的值的時候不處於活躍狀態導致沒有回調,當生命周期來到onStart的時候就會去回調。