事件发送后,观察者才订阅,订阅后会收到之前的事件。
当先订阅,后事件发送,
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
这里以setValue来分析,会调用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, ObserverWrapper>> iterator =
mObservers.iteratorWithAdditions(); iterator.hasNext(); ) {
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
因为initiator为null,所以会走else,然后遍历注册的observer。调用considerNotify().
private void considerNotify(ObserverWrapper observer) {
if (!observer.mActive) {
return;
}
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
observer.mObserver.onChanged((T) mData);
}
满足上面判断的条件,最后就会收到onChange()的通知,去做更新UI的操作。
而粘性事件是说先发送数据,再进行订阅,也会收到之前的数据。所以这个时候需要来看observe方法。
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);
}
会先把observer,和LifecycleOwner封装成LifecycleBoundObserver包装类,接着以Observer为key,新创建的LifecycleBoundObserver为value,存储到mObservers这个map中。在后面LiveData postValue中会遍历出该map的value值ObserverWrapper,获取组件生命周期的状态,已此状态来决定分不分发通知
@Override
public void addObserver(@NonNull LifecycleObserver observer) {
...代码省略...
while ((statefulObserver.mState.compareTo(targetState) < 0
&& mObserverMap.contains(observer))) {
pushParentState(statefulObserver.mState);
statefulObserver.dispatchEvent(lifecycleOwner, upEvent(statefulObserver.mState));
popParentState();
// mState / subling may have been changed recalculate
targetState = calculateTargetState(observer);
}
...代码省略...
}
此处会进入while循环,然后调用dispatchEvent方法,
void dispatchEvent(LifecycleOwner owner, Event event) {
State newState = getStateAfter(event);
mState = min(mState, newState);
mLifecycleObserver.onStateChanged(owner, event);
mState = newState;
}
然后会调用LifeCycleBoundObserver的onStateChanged方法
void activeStateChanged(boolean newActive) {
if (newActive == mActive) {
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) {
onActive();
}
if (LiveData.this.mActiveCount == 0 && !mActive) {
onInactive();
}
if (mActive) {
dispatchingValue(this);
}
}
}
这里又可以看到熟系的dispatchingValue(),它这里传的是this。然后后前面的流程一样,就可以接收到先前发送的数据。
会出现的场景为:
屏幕旋转
用户手动切换系统语言
下面用屏幕旋转场景来解释。
mTestViewModule.testLiveData.observe(this, new Observer() {
@Override
public void onChanged(Integer integer) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
runOnUiThread(new Runnable() {
@Override
public void run() {
startActivity(new Intent(MainActivity.this, CommonTabLayoutActivity.class));
}
});
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();
}
});
btn_test.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
mTestViewModule.getTestLiveData().setValue(3);
}
});
点击button,给getTestLiveData赋值,然后数值发生变化,上面就会监听到数据的变化,休眠三秒自动跳转到CommonTabLayoutActivity中,然后再返回到MainActivity中,将屏幕旋转,没有点击的操作,三秒过后,又可以看到会自动跳转到CommonTabLayoutActivity中。
这得从生命周期来分析,将屏幕旋转时,其生命周期为:onStop -> onRetainCustomNonConfigurationInstance -> onDestory -> getLastNonConfigurationInstance -> onCreate -> onStart -> onResume,在onCreate的时候会重新创建一个LifecycleBoundObserver实例,LifecycleBoundObserver继承ObserverWrapper,在ObserverWrapper中,会将mLastVersion重新赋值。而调用considerNotify的时候,会将mLastVersion和mVersion做判断。mVersion是在每次setValue或者postValue的时候都会递增。
private void considerNotify(ObserverWrapper observer) {
if (!observer.mActive) {
return;
}
if (!observer.shouldBeActive()) {
observer.activeStateChanged(false);
return;
}
if (observer.mLastVersion >= mVersion) {
return;
}
observer.mLastVersion = mVersion;
observer.mObserver.onChanged((T) mData);
}
而新创建的mLastVersion会被重新赋值为-1,小于mVersion,于是将会往下走,调用onChanged回调。
解决方法有四种:
关于LiveData粘性事件所带来问题的解决方案
参考文献:
关于LiveData粘性事件所带来问题的解决方案