EventBus原理與原始碼解析
1、概述
EventBus是針對Android優化的釋出-訂閱事件匯流排,簡化了Android元件間的通訊。EventBus以其簡單易懂、優雅、開銷小等優點而備受歡迎。關於其如何使用網上有很多教程,也可以從其 ofollow,noindex">官網 中瞭解到基本用法。其中整體事件流程的走向基本上可以用官網的一張圖來說明,如下:

EventBus-Publish-Subscribe.png
publisher通過post來傳遞事件到事件中心Bus,Bus再將事件分發到Subscriber。其本質是一個觀察者模型,最核心部分也就是Bus如何接收訊息和分發訊息。
2、基本概念:
在講解原始碼之前,先說一下EventBus需要關注的點 - EventBus支援的四種執行緒模式(ThreadMode)。如我們常常採用以下方式使用
@Subscribe(threadMode = ThreadMode.POSTING) public void getEventBus(Integer num) { if (num != null) { Toast.makeText(this, "num" + num, Toast.LENGTH_SHORT).show(); } }
其中 @Subscribe(threadMode = ThreadMode.POSTING)
也可以寫成 @Subscribe
。
1. POSTING(預設):事件在哪個執行緒釋出,就在哪個執行緒消費,因此要特別注意不要在UI執行緒進行耗時的操作,否則會ANR。
2. MAIN:事件的消費會在UI執行緒。因此,不宜進行耗時操作,以免引起ANR。
3. BACKGROUND:如果事件在UI執行緒產生,那麼事件的消費會在單獨的子執行緒中進行。否則,在同一個執行緒中消費。
4. ASYNC:不管是否在UI執行緒產生事件,都會在單獨的子執行緒中消費事件。
除此之外EventBus還支援粘性事件,即傳送一個未註冊的粘性事件,註冊者會在完成註冊之後收到這個粘性事件。
3、原始碼解析
正如官網圖和上文所說,EventBus最核心的部分就是其訊息註冊和分發中心,如何將訊息註冊者和訊息接收這繫結起來達到準確的分發,這個當是難點。接下來我們通過起原始碼來逐一分析和解讀。從 官網 中下載EventBus的原始碼,可以知道其原始碼並不是很多,整體結構基本如下:

eventbus_sources.png
原始碼結構相對來說是非常清晰了,大佬就是大佬。
我們開始使用EventBus的時候都會採用如下方式註冊使用
EventBus.getDefault().register(this);
通過檢視getDefault方法
/** Convenience singleton for apps using a process-wide EventBus instance. */ public static EventBus getDefault() { EventBus instance = defaultInstance; if (instance == null) { synchronized (EventBus.class) { instance = EventBus.defaultInstance; if (instance == null) { instance = EventBus.defaultInstance = new EventBus(); } } } return instance; }
發現是一個“雙重校驗鎖”的單例模式。
檢視EventBus
EventBus(EventBusBuilder builder) { logger = builder.getLogger(); subscriptionsByEventType = new HashMap<>(); typesBySubscriber = new HashMap<>(); stickyEvents = new ConcurrentHashMap<>(); mainThreadSupport = builder.getMainThreadSupport(); mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null; backgroundPoster = new BackgroundPoster(this); asyncPoster = new AsyncPoster(this); indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0; subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes, builder.strictMethodVerification, builder.ignoreGeneratedIndex); logSubscriberExceptions = builder.logSubscriberExceptions; logNoSubscriberMessages = builder.logNoSubscriberMessages; sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent; sendNoSubscriberEvent = builder.sendNoSubscriberEvent; throwSubscriberException = builder.throwSubscriberException; eventInheritance = builder.eventInheritance; executorService = builder.executorService; }
構造者,裡面會初始化一些基礎變數。
3.1註冊
public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass();//1 List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);//2 synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod);//3 } } }
subscribe
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class<?> eventType = subscriberMethod.eventType; Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//1 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);//2 if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<>(); subscriptionsByEventType.put(eventType, subscriptions);//3 } else { if (subscriptions.contains(newSubscription)) { throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType); } } int size = subscriptions.size(); for (int i = 0; i <= size; i++) { if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) { subscriptions.add(i, newSubscription); break; } } List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); if (subscriberMethod.sticky) {//4 if (eventInheritance) { // Existing sticky events of all subclasses of eventType have to be considered. // Note: Iterating over all events may be inefficient with lots of sticky events, // thus data structure should be changed to allow a more efficient lookup // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>). Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet(); for (Map.Entry<Class<?>, Object> entry : entries) { Class<?> candidateEventType = entry.getKey(); if (eventType.isAssignableFrom(candidateEventType)) { Object stickyEvent = entry.getValue(); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } } else { Object stickyEvent = stickyEvents.get(eventType); checkPostStickyEventToSubscription(newSubscription, stickyEvent); } } }
- 將註冊者和事件消費方法封裝起來,這裡才是真正的繫結。
- 就像上述註冊者和事件消費方法是1:N的關係。一個Event與註冊者之間也是1:N的關係。因為一個Event可能會被不同的Activity註冊。也就是說Event、註冊者、事件消費方法的關係是:1:N:M(其中M、N均大於等於1)。
- 註冊者(比如MainActivity.this)與事件消費方法(SubscriberMethod)的關係,我們封裝到了Subscription(s)中了。而Event和Subscription(s)的關係,我們通過HashMap儲存,key為event.class,value即Subscription(s)。
- 黏性事件的處理。
3.2釋出與消費
public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); if (!postingState.isPosting) { postingState.isMainThread = isMainThread(); postingState.isPosting = true; if (postingState.canceled) { throw new EventBusException("Internal error. Abort state was not reset"); } try { while (!eventQueue.isEmpty()) { postSingleEvent(eventQueue.remove(0), postingState);//1 } } finally { postingState.isPosting = false; postingState.isMainThread = false; } } }
- 通過前面的狀態判斷,走到這一步真正消費事件。繼續往下走該方法,我們可以發現其最終是呼叫方法
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case POSTING: invokeSubscriber(subscription, event); break; case MAIN: if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case MAIN_ORDERED: if (mainThreadPoster != null) { mainThreadPoster.enqueue(subscription, event); } else { // temporary: technically not correct as poster not decoupled from subscriber invokeSubscriber(subscription, event); } break; case BACKGROUND: if (isMainThread) { backgroundPoster.enqueue(subscription, event); } else { invokeSubscriber(subscription, event); } break; case ASYNC: asyncPoster.enqueue(subscription, event); break; default: throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode); } }
從程式碼可以知道,最終會通過判斷執行緒,來依次消費事件。
檢視方法 invokeSubscriber(subscription, event);
void invokeSubscriber(Subscription subscription, Object event) { try { subscription.subscriberMethod.method.invoke(subscription.subscriber, event); } catch (InvocationTargetException e) { handleSubscriberException(subscription, event, e.getCause()); } catch (IllegalAccessException e) { throw new IllegalStateException("Unexpected exception", e); } }
可以看出最終是以反射的方式。
3.3 反註冊
註冊消費完事件後,我們需要反向註冊,類似如我們廣播的使用。
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) { List<Subscription> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions != null) { int size = subscriptions.size(); for (int i = 0; i < size; i++) { Subscription subscription = subscriptions.get(i); if (subscription.subscriber == subscriber) { subscription.active = false; subscriptions.remove(i); i--; size--; } } } }
可以看到是依次移除掉 subscriptions
列表。
4、總結
從整個程式碼流程來看,基本上沒什麼難點,用起來也非常方便。
但在使用過程中,像我這種菜鳥發現了兩個問題
-
其訊息給人感覺是一種亂跳的感覺,因為其採用註解的方式,這點感覺對業務邏輯梳理並不一定佔有優勢,就拿Android Studio來說,居然會提示該方法無處使用,如下圖:
no_use.png
- 採用反射方法
invokeSubscriber
來消費事件,效率如何。