在跨页面使用LiveData时出现新的页面刚订阅上事件就被触发了一次事件接收,类似用Rxbus或者EventBus的粘连性事件,然后网上搜索了一下,发现很少有此类文章.没办法只好自己看看LiveData的源码,还好它的源码不多,发现关键点在于
private abstract class ObserverWrapper {
final Observer<? super T> mObserver;
boolean mActive;
// 关键点
int mLastVersion = START_VERSION;
ObserverWrapper(Observer<? super T> observer) {
mObserver = observer;
}
abstract boolean shouldBeActive();
boolean isAttachedTo(LifecycleOwner owner) {
return false;
}
void detachObserver() {
}
新的订阅事件的mLastVersion 等于-1,所以只要在他订阅之前如果有发送过Data 那么新注册的事件的mLastVersion就小于LiveData的mVersion
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);
}
所以只需要修改下mLastVersion的初始化逻辑就能解决此类问题
完整代码和demo已上传github
StickyLiveData