簡介
源碼基于 org.greenrobot:eventbus:3.2.0
EventBus是Android和Java的發(fā)布/訂閱事件總線。
使用步驟
- 自定義消息
public static class MessageEvent {
//可以根據(jù)業(yè)務(wù)需求添加所需的字段
public int code;//定義一個業(yè)務(wù)code,可區(qū)分不同消息
}
- 聲明并注解訂閱方法,可以指定運行線程
@Subscribe(threadMode = ThreadMode.MAIN) //ThreadMode.MAIN指定在主線程運行
public void onMessageEvent(MessageEvent event) {
//獲取到MessageEvent消息體后,可在這進(jìn)行業(yè)務(wù)處理
};
- 在Activity生命周期注冊和反注冊EventBus
@Override
public void onStart() {
super.onStart();
//注冊
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
//反注冊
EventBus.getDefault().unregister(this);
}
- 準(zhǔn)備完畢后,就可以開始發(fā)送一個自定義消息MessageEvent
//可以在主線程也可在非主線程進(jìn)行發(fā)送
EventBus.getDefault().post(new MessageEvent());
以上就是EventBus的簡單使用,下面來分析一下EventBus,自定義消息如何發(fā)送到指定方法上去并且在是如何指定運行線程。
原理分析(圖片)
準(zhǔn)備分析前,先通過圖來簡單說明一下大致流程
- 剛開始,我們未訂閱任何方法和未發(fā)送任何消息事件

image.png
-
假設(shè)在EventActivity訂閱一個onMessageEvent方法,并且該方法接收MessageEvent消息事件,剛開始相互沒有關(guān)聯(lián)
image.png 當(dāng)Activity調(diào)用onStart時候,EventBus進(jìn)行了注冊,這個時候就開始關(guān)聯(lián)起來,
@Override
public void onStart() {
super.onStart();
//注冊
EventBus.getDefault().register(this);
}

image.png
相應(yīng)的,當(dāng)反注冊的時候,將移除對應(yīng)關(guān)系
-
發(fā)送消息事件
image.png
原理分析(源代碼)
EventBus使用了單利模式,所以全局只有一個EventBus實例,使用DLC
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里面2個字段,都是Map+List的數(shù)據(jù)格式
第一個是存放一個消息類型對應(yīng)的全部訂閱方法
第二個是存放和注冊對象有關(guān)聯(lián)的消息類型
//根據(jù)消息事件類型進(jìn)行存儲所有訂閱方法
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
//根據(jù)注冊的實例存儲當(dāng)前對象訂閱方法所有接收消息事件
private final Map<Object, List<Class<?>>> typesBySubscriber;
以我們前面使用步驟代碼為例,假設(shè)當(dāng)前代碼在EventActivity
class EventActivity{
//消息
public static class MessageEvent { }
//訂閱方法
@Subscribe(threadMode = ThreadMode.MAIN) //ThreadMode.MAIN指定在主線程運行
public void onMessageEvent(MessageEvent event) { };
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
}
通過注冊進(jìn)行關(guān)聯(lián)
public void register(Object subscriber) {
//獲取注冊對象的類類型,這里是EventActivity.class
Class<?> subscriberClass = subscriber.getClass();
//根據(jù)注解獲取EventActivity所有訂閱方法,并且封裝為SubscriberMethod對象,因為Activity可以訂閱多個方法,
//所以最終返回的是一個數(shù)組
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
//遍歷所有訂閱方法,將訂閱方法存放到指定的位置
for (SubscriberMethod subscriberMethod : subscriberMethods) {
//訂閱
subscribe(subscriber, subscriberMethod);
}
}
}

圖示返回3個SubscriberMethod,比較好表示為數(shù)組,實際應(yīng)該返回1個
接下來繼續(xù)看如何進(jìn)行訂閱
//訂閱
//Object subscriber這里為EventActivty對象
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//獲取訂閱方法接收的消息類型,這里為MessageEvent.class
Class<?> eventType = subscriberMethod.eventType;
//將EventActivity對象和訂閱方法組合為Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//根據(jù)消息類型獲取該消息存放訂閱方法的數(shù)組
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
//為空,也就是該消息第一次訂閱,則創(chuàng)建一個新的數(shù)組,并且添加到map中
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//同一個訂閱方法不能重復(fù)訂閱
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
//這里主要是根據(jù)優(yōu)先級將訂閱方法插入指定位置
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
//將訂閱方法插入數(shù)組,這樣就完成一次訂閱方法的添加
subscriptions.add(i, newSubscription);
break;
}
}
//獲取該對象(EventActivity)全部訂閱方法接收的消息事件
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
//第一次創(chuàng)建一個并且設(shè)置到map
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
//添加消息類型
subscribedEvents.add(eventType);
...
}

image.png
發(fā)送一個MessageEvent
public void post(Object event) {
//獲取當(dāng)前線程的PostingThreadState
PostingThreadState postingState = currentPostingThreadState.get();
//獲取消息隊列
List<Object> eventQueue = postingState.eventQueue;
//將消息加入隊列
eventQueue.add(event);
if (!postingState.isPosting) {
//如果空閑狀態(tài),則觸發(fā)進(jìn)行消息發(fā)送
//獲取當(dāng)前線程是否主線程
postingState.isMainThread = isMainThread();
//標(biāo)記正在發(fā)送消息
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) {
//循環(huán)從隊列獲取消息,直到隊列為空
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
//重置狀態(tài)
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//獲取當(dāng)前消息的類類型,這里是MessagEvent.class
Class<?> eventClass = event.getClass();
//是否找到訂閱方法
boolean subscriptionFound = false;
if (eventInheritance) {
//是否查詢MessagEvent.class的父類類型,也就是父類型的消息訂閱的方法也要進(jìn)行發(fā)送
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
//發(fā)送消息
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
//發(fā)送消息
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
if (!subscriptionFound) {
//未找到訂閱方法進(jìn)行相應(yīng)處理
if (logNoSubscriberMessages) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
//定義一個訂閱方法的數(shù)組
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//根據(jù)事件類型獲取全部訂閱方法的數(shù)組
subscriptions = subscriptionsByEventType.get(eventClass);
}
//存在訂閱方法
if (subscriptions != null && !subscriptions.isEmpty()) {
//遍歷所有訂閱方法
for (Subscription subscription : subscriptions) {
//標(biāo)記當(dāng)前發(fā)送的事件和訂閱方法
postingState.event = event;
postingState.subscription = subscription;
boolean aborted;
try {
//發(fā)送事件
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
//重置
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
//如果中途中斷則跳出循環(huán)
break;
}
}
return true;
}
return false;
}
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case POSTING://在哪個線程發(fā)送消息,就在哪個線程進(jìn)行接收處理
invokeSubscriber(subscription, event);
break;
case MAIN://主線程接收處理
if (isMainThread) {
//當(dāng)前是主線程,直接發(fā)送
invokeSubscriber(subscription, event);
} else {
//當(dāng)前非主線程,則通過mainThreadPoster發(fā)送到主線程
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);
}
}
void invokeSubscriber(Subscription subscription, Object event) {
try {
//通過反射調(diào)用訂閱方法,完成一次消息發(fā)送
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
子線程切換成主線程
//主線程HandlerPoster繼承自Handler
public class HandlerPoster extends Handler implements Poster {
private final PendingPostQueue queue;
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
protected HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
super(looper);
this.eventBus = eventBus;
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
//消息入隊
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
//發(fā)送消息到主線程的Looper
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
//接收到消息處理,后面流程就是進(jìn)行反射調(diào)用訂閱方法
//這樣就完成一次子線程到主線程的切換
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
//反射調(diào)用
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
}
主線程切換成子線程
final class BackgroundPoster implements Runnable, Poster {
//隊列
private final PendingPostQueue queue;
private final EventBus eventBus;
private volatile boolean executorRunning;
BackgroundPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
//消息入隊
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
//通過EventBus的線程池執(zhí)行
//這樣就完成一次主線程到子線程的切換
eventBus.getExecutorService().execute(this);
}
}
}
@Override
public void run() {
try {
try {
while (true) {
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
//反射調(diào)用
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
}
最后看下反注冊如何處理
public synchronized void unregister(Object subscriber) {
//根據(jù)注冊對象獲取消息事件類型數(shù)組
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
//循環(huán)消息類型數(shù)組
unsubscribeByEventType(subscriber, eventType);
}
//移除該數(shù)組
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根據(jù)消息事件類型獲取訂閱方法數(shù)組
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--;
}
}
}
}
這樣就反注冊移除全部訂閱方法
總結(jié)
準(zhǔn)備階段
- 創(chuàng)建消息事件對象
- 添加一個訂閱方法并且添加注解
- 調(diào)用EventBus進(jìn)行注冊
發(fā)送階段
- 通過EventBus.post發(fā)送前面創(chuàng)建的消息事件對象
注銷階段
- 調(diào)用EventBus進(jìn)行注銷,清空之前訂閱的方法

