知道了EventBus的注冊(cè)流程后,我們來(lái)了解一下EventBus發(fā)布事件的流程。如果還沒(méi)看過(guò)注冊(cè)流程,建議先瀏覽:
Android必知必會(huì)的EventBus之使用篇
Android必知必會(huì)的EventBus源碼分析之注冊(cè)
我們知道EventBus的發(fā)布事件一行代碼解決
EventBus.getDefault().post(new MessageEvent());
MessageEvent是我們?cè)谄渌胤接嗛喌氖录愋?。接著我們看?code>post方法。
/** Posts the given event to the event bus. */
public void post(Object event) {
//通過(guò)ThreadLocal獲取當(dāng)前線程的狀態(tài)
PostingThreadState postingState = currentPostingThreadState.get();
//獲取當(dāng)前線程的事件隊(duì)列
List<Object> eventQueue = postingState.eventQueue;
//將我們發(fā)送的類型事件添加到隊(duì)列中
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()) {
//當(dāng)隊(duì)列不為空是,不停的發(fā)送單一事件,知道隊(duì)列為空
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
通過(guò)上面代碼,我們知道EventBus的post方法通過(guò)本地線程ThreadLocal去獲取事件隊(duì)列。并將我們發(fā)布的事件類型添加到隊(duì)列中。在隊(duì)列eventQueue不為空的情況,調(diào)用postSingleEvent方法。我們看看postSingleEvent方法。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//默認(rèn)情況為true
if (eventInheritance) {
//查看父類或者父接口是否有該事件類型
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
if (!subscriptionFound) {
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));
}
}
}
通過(guò)上面代碼,我們知道最終會(huì)調(diào)用postSingleEventForEventType。
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
return true;
}
return false;
}
通過(guò)上一篇文章,我們知道,subscriptions存放著事件的訂閱類和訂閱方法。讓我們看看postToSubscription方法。
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);
}
}
通過(guò)代碼可以發(fā)現(xiàn),EventBus的線程切換在此次。至于不同參考EventBus的使用這里我們先看看invokeSubscriber方法。
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);
}
}
因此,我們知道,在注冊(cè)過(guò)程中,通過(guò)注解和反射機(jī)制,將相關(guān)的訂閱類和方法包裝到了Subscription。在此次,切換線程后,再調(diào)用Subscription中的訂閱方法。到這里,發(fā)布事件流程就結(jié)束了。
至于黏性事件的發(fā)布,原理應(yīng)該差不多,大家可以自行查閱。