1、概述
EventBus是針對Android優(yōu)化的發(fā)布-訂閱事件總線,簡化了Android組件間的通信。EventBus以其簡單易懂、優(yōu)雅、開銷小等優(yōu)點而備受歡迎。關于其如何使用網(wǎng)上有很多教程,也可以從其官網(wǎng)中了解到基本用法。其中整體事件流程的走向基本上可以用官網(wǎng)的一張圖來說明,如下:

publisher通過post來傳遞事件到事件中心Bus,Bus再將事件分發(fā)到Subscriber。其本質是一個觀察者模型,最核心部分也就是Bus如何接收消息和分發(fā)消息。
關于整體調用于2020年元旦整理了以下流程:

流程大體如此圖。
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType 是一個key&value的結構,該對象也是整個框架的數(shù)據(jù)存放點,無論是注冊-發(fā)送-反注冊都是在此集合中查找刪除等相關操作。
關于如何做到線程之間的切換,最主要的是先判斷是否是主線程,若是主線程則直接反射調用,若不是,則創(chuàng)建子線程,在子線程中調用
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(默認):事件在哪個線程發(fā)布,就在哪個線程消費,因此要特別注意不要在UI線程進行耗時的操作,否則會ANR。
2. MAIN:事件的消費會在UI線程。因此,不宜進行耗時操作,以免引起ANR。
3. BACKGROUND:如果事件在UI線程產生,那么事件的消費會在單獨的子線程中進行。否則,在同一個線程中消費。
4. ASYNC:不管是否在UI線程產生事件,都會在單獨的子線程中消費事件。
除此之外EventBus還支持粘性事件,即發(fā)送一個未注冊的粘性事件,注冊者會在完成注冊之后收到這個粘性事件。
3、源碼解析
正如官網(wǎng)圖和上文所說,EventBus最核心的部分就是其消息注冊和分發(fā)中心,如何將消息注冊者和消息接收這綁定起來達到準確的分發(fā),這個當是難點。接下來我們通過起源碼來逐一分析和解讀。從官網(wǎng)中下載EventBus的源碼,可以知道其源碼并不是很多,整體結構基本如下:

源碼結構相對來說是非常清晰了,大佬就是大佬。
我們開始使用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;
}
發(fā)現(xiàn)是一個“雙重校驗鎖”的單例模式。
查看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
}
}
}
- 獲取注冊的者上下文,比如說Activity
- 通過注冊者的上下文查找注冊的事件方法
- 將注冊者和注冊的事件綁定起來,即完成了注冊,可以查看
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發(fā)布與消費
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;
}
}
}
- 通過前面的狀態(tài)判斷,走到這一步真正消費事件。繼續(xù)往下走該方法,我們可以發(fā)現(xiàn)其最終是調用方法
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、總結
從整個代碼流程來看,基本上沒什么難點,用起來也非常方便。
但在使用過程中,像我這種菜鳥發(fā)現(xiàn)了兩個問題
-
其消息給人感覺是一種亂跳的感覺,因為其采用注解的方式,這點感覺對業(yè)務邏輯梳理并不一定占有優(yōu)勢,就拿Android Studio來說,居然會提示該方法無處使用,如下圖:
no_use.png - 采用反射方法
invokeSubscriber來消費事件,效率如何。
