ViewModel:
負責為關聯UI(activity/fragment)進行數據管理,業務邏輯處理。不直接持有view引用,不對UI進行訪問調用操作
對外通過暴露Livedata方式響應處理結果
LiveData:
可感知組件生命周期、被觀察的數據源,在數據發生改變時進行通知提醒
ViewModel處理數據后使用LiveData通知到observer數據已變更,
Lifecycle:
對象or組件生命周期狀態定義接口,實現子類LifecycleRegistry。包含LifeCycleOwer和LifecycleObserver,分別是生命周期所有者和生命周期感知者
Lifecycle定義組件狀態

ViewModel創建存儲流程:

組件與Livedata,Observer,Lifecycle關聯流程:

Livedata observe()
@MainThread
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<T> observer) {//已銷毀組件不作處理
if (owner.getLifecycle().getCurrentState() == DESTROYED) {
// ignore
return;
}
//包裝observer包含組件生命狀態監控的LifecycleBoundObserver
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;
}
//添加到Lifecyvle內保存
owner.getLifecycle().addObserver(wrapper);
}
LiveData 添加LifecycleBoundObserver到LifecycleRegister內處理:
public class LifecycleRegistry extends Lifecycle {
@Override
public void addObserver(LifecycleObserver observer) {
State initialState = mState == DESTROYED ? DESTROYED : INITIALIZED;
//通過ObserverWithState包裝LifecycleObserver內部進行操作管理
ObserverWithState statefulObserver = new ObserverWithState(observer, initialState);
ObserverWithState previous = mObserverMap.putIfAbsent(observer, statefulObserver);
......
}
......
ObserverWithState負責分發組件狀態變化,與關聯的LifecycleBoundObserver狀態關聯
static class ObserverWithState {
State mState;
GenericLifecycleObserver mLifecycleObserver;
ObserverWithState(LifecycleObserver observer, State initialState) {
mLifecycleObserver = Lifecycling.getCallback(observer);
mState = initialState;
}
//分發組件狀態到所關聯Observer
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
}
看一下 LifecycleBoundObserver內部代碼
class LifecycleBoundObserver extends ObserverWrapper implements GenericLifecycleObserver {
@NonNull final LifecycleOwner mOwner;
LifecycleBoundObserver(@NonNull LifecycleOwner owner, Observer<T> observer) {
super(observer);
mOwner = owner;
}
......
//當組件周期狀態變化時,處理關聯的Observer
@Override
public void onStateChanged(LifecycleOwner source, Lifecycle.Event event) {
if (mOwner.getLifecycle().getCurrentState() == DESTROYED) {
removeObserver(mObserver);
return;
}
activeStateChanged(shouldBeActive());
}
......
}
private abstract class ObserverWrapper {
final Observer<T> mObserver;
boolean mActive;
int mLastVersion = START_VERSION;
ObserverWrapper(Observer<T> observer) {
mObserver = observer;
}
......
void activeStateChanged(boolean newActive) {//組件周期變化時判斷是否需要重新分發value data
if (newActive == mActive) {//observe與組件狀態一致時不處理,
return;
}
// immediately set active state, so we'd never dispatch anything to inactive
// owner
mActive = newActive;
boolean wasInactive = LiveData.this.mActiveCount == 0;
LiveData.this.mActiveCount += mActive ? 1 : -1;
if (wasInactive && mActive) {//LiveData從非活躍到激活狀態
onActive();
}
if (LiveData.this.mActiveCount == 0 && !mActive) {//LiveData從激活到非活躍狀態
onInactive();
}
if (mActive) {//組件激活狀態時重新分發上一次存留數據
dispatchingValue(this);
}
}
}
LifeData分發數據處理:
setValue修改數據
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");//主線程調用
mVersion++;//每次修改,版本號+1
mData = value;
dispatchingValue(null);//數據分發處理
}
private void dispatchingValue(@Nullable ObserverWrapper initiator) {
if (mDispatchingValue) {
mDispatchInvalidated = true;
return;
}
mDispatchingValue = true;
do {
mDispatchInvalidated = false;
if (initiator != null) {//分發給指定observer
considerNotify(initiator);
initiator = null;
} else {//分發Observer列表內所有注冊對象
for (Iterator<Map.Entry<Observer<T>, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
private void considerNotify(ObserverWrapper observer) {
if (!observer.mActive) {//非激活狀態不處理
return;
}
// 是否為active狀態
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}//observer dataVersion大於等於LiveData dataVersion不予處理
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
//通知Observer change數據
observer.mObserver.onChanged((T) mData);
}
整體大致流程:

