相比RxBus猜极,EventBus,LiveData有個(gè)非常簡(jiǎn)單的LiveEventBus
參考文章
類(lèi)似github 項(xiàng)目
如果了解JetPacks原理需要查看我的文章
JetPacks之Lifecycles 原理分析
我們自定義分析下原理
貼一下我們的自定義工具類(lèi)
public class LiveDataBus {
//存放訂閱者
private Map<String, MutableLiveData<Object>> bus;
private static LiveDataBus liveDataBus = new LiveDataBus();
private LiveDataBus() {
bus = new HashMap();
}
public static LiveDataBus getInstance() {
return liveDataBus;
}
//注冊(cè)訂閱者
public synchronized <T> MutableLiveData<T> with(String key, Class<T> type) {
if(!bus.containsKey(key)){
bus.put(key,new MutableLiveData<Object>());
}
return (MutableLiveData<T>)bus.get(key);
}
}
實(shí)驗(yàn)
做一個(gè)頁(yè)面跳轉(zhuǎn)椭符,第一個(gè)頁(yè)面?zhèn)鬟f數(shù)據(jù)給第二個(gè)頁(yè)面
5s發(fā)送一個(gè)數(shù)據(jù)。分別看下LiveDataBus 和LiveDataBusX「接續(xù)往下看會(huì)實(shí)現(xiàn)這個(gè)」粘性數(shù)據(jù)
-> 第一個(gè)頁(yè)面
public void startLiveDataBusActivity() {
//-> LiveDataBus 換成 LiveDataBusX 解決粘性
//-> 粘性數(shù)據(jù)執(zhí)行
//-> new LiveData() ——> 綁定Observer —> setValue(onChanged) 正常LiveDataBusX
//-> new LiveData() ——> setValue(onChanged) —> 綁定Observer LiveDataBus
Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setClass(context, TestLiveDataBusActivity.class);
context.startActivity(intent);
new Thread() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
//發(fā)送消息
LiveDataBus.getInstance().with("data", String.class).postValue("David-LiveDataBus");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
我們?cè)赥estLiveDataBusActivity 這個(gè)頁(yè)面進(jìn)行接收
public class TestLiveDataBusActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_live_data_bus);
//-> 測(cè)試 要吧MainActivity LiveDataBus和LiveDataBusX 保持一致
LiveDataBus.getInstance().with("data",String.class)
.observe(this, new Observer<String>() {
@Override
public void onChanged(String s) {
if(s!=null)
Toast.makeText(TestLiveDataBusActivity.this, s, Toast.LENGTH_SHORT).show();
}
});
}
}
我們會(huì)發(fā)現(xiàn)可能某些場(chǎng)景我們不適合用
我們正常的思維
new LiveData() ——> 綁定Observer —> setValue(onChanged)
先綁定在設(shè)置值
而這里忽略我們的順序變成
new LiveData() ——> setValue(onChanged) —> 綁定Observer -> setValue(onChanged)
和LiveData原理實(shí)現(xiàn)有關(guān), 我們可以用反射切斷第一次的onChange
解決這個(gè)bug耻姥,用反射處理
-> 「找Hook 點(diǎn)」
再次我們閱讀源碼
找到我們的入口
//發(fā)送消息
LiveDataBus.getInstance().with("data", String.class).postValue("David-LiveDataBus");
兜了一圈销钝,你會(huì)發(fā)現(xiàn),會(huì)切換線程琐簇,并且給指向setValue方法蒸健。
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
-> 繼續(xù)進(jìn)入查看
dispatchingValue(null);
}
需要注意-----------》 我們dipatchingValue傳入的一開(kāi)始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(); ) {
-> 初始值null參數(shù),所以我們會(huì)走for循環(huán)
considerNotify(iterator.next().getValue());
if (mDispatchInvalidated) {
break;
}
}
}
} while (mDispatchInvalidated);
mDispatchingValue = false;
}
considerNotify ---------> 這里我們發(fā)現(xiàn)了private實(shí)現(xiàn)婉商,并且是靠version判斷似忧。貌似是Hook的切入點(diǎn)
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);
}
從這個(gè)方法我們知道改變mLastVersion 和mVersion的值就可以了。mLastVersion 初始化值 -1据某。執(zhí)行過(guò)程不一定橡娄。但是確實(shí)mLastVersion < mVersion 導(dǎo)致繼續(xù)向下執(zhí)行
我們需要從這里反向退,最好反向看找到最終的調(diào)用點(diǎn)
-> 這個(gè)是我們推出來(lái)的反射點(diǎn)
SafeIterableMap<Observer<? super T>, ObserverWrapper> mObservers
//ObserverWrapper initiator-> 發(fā)現(xiàn)迭代mObservers
void dispatchingValue(@Nullable ObserverWrapper initiator)
-> considerNotify(iterator.next().getValue());
private void considerNotify(ObserverWrapper observer) {
observer.mLastVersion
-> 反射實(shí)現(xiàn)代碼
public class LiveDataBusX {
//存放訂閱者
private Map<String, BusMutableLiveData<Object>> bus;
private static LiveDataBusX liveDataBus = new LiveDataBusX();
private LiveDataBusX() {
bus = new HashMap<>();
}
public static LiveDataBusX getInstance() {
return liveDataBus;
}
//注冊(cè)訂閱者癣籽,(存入map) Hook前用MutableLiveData
public synchronized <T> BusMutableLiveData<T> with(String key, Class<T> type) {
if (!bus.containsKey(key)) {
bus.put(key, new BusMutableLiveData<Object>());
}
return (BusMutableLiveData<T>) bus.get(key);
}
public static class BusMutableLiveData<T> extends MutableLiveData<T> {
@Override
public void observe(@NonNull LifecycleOwner owner, @NonNull Observer<? super T> observer) {
super.observe(owner, observer);
hook(observer);
}
//在這里去改變onChange的流程
private void hook(Observer<? super T> observer) {
try {
//1.得到mLastVersion
//獲取到LiveData的類(lèi)中的mObservers對(duì)象
Class<LiveData> liveDataClass = LiveData.class;
Field mObserversField = liveDataClass.getDeclaredField("mObservers");
mObserversField.setAccessible(true);
//獲取到這個(gè)成員變量的對(duì)象
Object mObserversObject = mObserversField.get(this);
//得到map對(duì)應(yīng)的class對(duì)象
Class<?> mObserversClass = mObserversObject.getClass();
//獲取到mObservers對(duì)象的get方法
Method get = mObserversClass.getDeclaredMethod("get", Object.class);
get.setAccessible(true);
//執(zhí)行g(shù)et方法
Object invokeEntry = get.invoke(mObserversObject, observer);
//定義一個(gè)空的對(duì)象
Object observerWraper = null;
if (invokeEntry != null && invokeEntry instanceof Map.Entry) {
observerWraper = ((Map.Entry) invokeEntry).getValue();
}
if (observerWraper == null) {
throw new NullPointerException("observerWraper is null");
}
//得到ObserverWrapper的類(lèi)對(duì)象 編譯擦除問(wèn)題會(huì)引起多態(tài)沖突所以用getSuperclass
Class<?> superclass = observerWraper.getClass().getSuperclass();
Field mLastVersion = superclass.getDeclaredField("mLastVersion");
mLastVersion.setAccessible(true);
//2.得到mVersion
Field mVersion = liveDataClass.getDeclaredField("mVersion");
mVersion.setAccessible(true);
//3.把mVersion的數(shù)據(jù)填入到mLastVersion中
Object mVersionValue = mVersion.get(this);
mLastVersion.set(observerWraper, mVersionValue);
} catch (Exception e) {
e.printStackTrace();
}
}
}