csdn博客:http://blog.csdn.net/hjjdehao
在看源碼之前,需要掌握的主要知識點:集合、反射、注解。
框架基本上是用這三方面的知識點寫的,沒掌握的最好去掌握下,不然看的時候會暈頭轉向。
一、注冊源碼解析
注冊的一系列流程,其流程圖(來自網絡)如下:

我們在使用EventBus的時候,首先做的第一件事就是給事件注冊對象了,通俗來講就是說要接收消息,需要登記信息,方便有消息可以通知到你。
那么EventBus是如何注冊信息的呢?又是如何接收事件?
我們帶著疑問看代碼,效果會更好。
注冊訂閱者代碼:
//將當前對象進行注冊,表示這個對象要接收事件
EventBus.getDefault().register(this);
注冊源碼:
public void register(Object subscriber) {
//獲取訂閱者的Class類型
Class<?> subscriberClass = subscriber.getClass();
//根據訂閱者的Class類型,獲取訂閱者的訂閱方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
List< SubscriberMethod > subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
這句代碼表示的是:通過訂閱者的Class類型獲取訂閱者的所有的訂閱方法。那它是如何獲取所有的訂閱方法的呢?
我們再看一下findSubscriberMethods方法的源碼
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//先從緩存中查找是否存在訂閱方法
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//是否忽略注解器生成的MyEventBusIndex類
if (ignoreGeneratedIndex) {
//利用反射來獲取訂閱類中的訂閱方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//從注解器生成的MyEventBusIndex類中獲得訂閱類的訂閱方法信息
subscriberMethods = findUsingInfo(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
上面的源碼在查找訂閱方法信息是用了兩種方式,如下所示:
if (ignoreGeneratedIndex) {
//利用反射來獲取訂閱類中的訂閱方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//從注解器生成的MyEventBusIndex類中獲得訂閱類的訂閱方法信息
subscriberMethods = findUsingInfo(subscriberClass);
}
ignoreGeneratedIndex的判斷是看你的build配置文件是否配置相關注解處理器信息如下:
要說兩種方式區(qū)別無非就是性能和速度,相對說注解處理比反射來的好,看下面的圖就清楚了。
這個方法的大致邏輯是這樣:
先從緩存中查找訂閱方法信息,如果沒有就利用反射或注解來獲取訂閱方法信息。
1、使用注解處理器
findUsingInfo(Class< ? > subscriberClass)
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
EventBus提供了一個EventBusAnnotationProcessor注解處理器來在編譯期通過讀取@Subscribe()注解并解析,
處理其中所包含的信息,然后生成java類來保存所有訂閱者關于訂閱的信息,這樣就比在運行時使用反射來獲得這些訂閱者的
信息速度要快。
EventBus 3.0使用的是編譯時注解,而不是運行時注解。通過索引的方式去生成回調方法表,通過表可以看出,極大的提高了性能。

2、通過反射獲取的訂閱方法信息
findUsingReflection(subscriberClass)源碼
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//通過發(fā)射獲得訂閱方法信息
findUsingReflectionInSingleClass(findState);
//查找父類的訂閱方法信息
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
FindState是一個實體類,用來保存訂閱者和訂閱方法的信息,以及校驗訂閱方法。寫了那么多,其實最終是調用findUsingReflectionInSingleClass(findState)來獲得訂閱方法的相關信息。
看代碼:
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
//獲取訂閱者的所有訂閱方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
//獲取訂閱方法的修飾權限
int modifiers = method.getModifiers();
//如果是public修飾的方法且不是靜態(tài)的和抽象的,否則拋出異常
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//獲取方法的參數類型數組
Class<?>[] parameterTypes = method.getParameterTypes();
//方法至少要有一個參數,否則拋出異常
if (parameterTypes.length == 1) {
//獲取注解對象
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
//獲取事件對象的參數類型信息
Class<?> eventType = parameterTypes[0];
//檢查是否添加了訂閱方法
if (findState.checkAdd(method, eventType)) {
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}
開始訂閱事件的源碼:
訂閱者有了,訂閱方法也有了。接下來是當做參數進行訂閱,
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//獲取事件類型
Class<?> eventType = subscriberMethod.eventType;
//實例一個訂閱者信息
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//根據事件類型獲取訂閱者對象
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
int size = subscriptions.size();
//根據優(yōu)先級來添加訂閱者對象
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) {
if (eventInheritance) {
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);
}
}
}
注冊只有一句代碼,但是深入里面去,卻是做了許許多多的工作。
其實,做了那么多的工作,無非就是存儲訂閱者的相關信息(訂閱者、訂閱方法、事件對象等),為后面的事件分發(fā)做的鋪墊。
訂閱邏輯:
1. 首先調用register()注冊訂閱對象。
2. 根據訂閱對象獲取該訂閱對象的所有訂閱方法。
3. subscriptionsByEventType.put(eventType, subscriptions),根據該訂閱者的所有訂閱的事件類型,將訂閱者存入到每個以 事件類型為key, 以訂閱者信息(subscriptions)為values的map集合中。
4. typesBySubscriber.put(subscriber, subscribedEvents),然后將訂閱事件添加到以訂閱者為key ,以訂閱者所有訂閱事件為values的map集合中.
二、事件分發(fā)解析
事件分發(fā)的流程圖(來源網絡)

注冊訂閱者是為了后面的事件分發(fā),以便知道該將事件發(fā)送給誰,而事件的接收就是訂閱者的訂閱方法。
事件分發(fā)代碼:
EventBus.getDefault().post(new Event());
看post方法的源碼:
參數即要發(fā)送的事件對象
public void post(Object event) {
//獲取當前線程的狀態(tài)
PostingThreadState postingState = currentPostingThreadState.get();
//獲取當前線程的事件隊列
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
//判斷當前線程是否處于發(fā)送狀態(tài)
if (!postingState.isPosting) {
//設置為主線程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
//不斷從隊列中循環(huán)取出事件
try {
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
PostingThreadState 是EventBust的靜態(tài)內部類,它保存當前線程的事件隊列和線程狀態(tài)。
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();//當前線程的事件隊列
boolean isPosting;//是否有事件正在分發(fā)
boolean isMainThread;//post的線程是否是主線程
Subscription subscription;//訂閱者
Object event;//訂閱事件
boolean canceled;//是否取消
}
參數一:事件對象
參數二:發(fā)送狀態(tài)
postSingleEvent(eventQueue.remove(0), postingState)執(zhí)行源碼
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
//獲取事件對象的Class類型
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//判斷事件對象是否有父類對象
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) {
Log.d(TAG, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
postSingleEventForEventType(event, postingState, eventClass)
看了那么多的源碼才發(fā)現這個方法才是罪魁禍首。最終發(fā)射事件的方法。
那好接著看看他的源碼:
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;
}
postToSubscription(subscription, event, postingState.isMainThread);
開始處理訂閱者的信息
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 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);
}
}
事件分發(fā)邏輯:
1. 獲取事件隊列。
2. 循環(huán)取出隊列中的事件。
3. 獲取訂閱者集合,然后遍歷,最后通過反射調用訂閱者的訂閱方法。
三、取消注冊解析
public synchronized void unregister(Object subscriber) {
//根據訂閱者獲取訂閱者的所有訂閱的事件類型
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
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--;
}
}
}
}
取消注冊邏輯:
1、首先根據訂閱者獲取所有訂閱事件。
2、遍歷訂閱事件集合。
3、根據訂閱事件獲取訂閱該事件的訂閱者集合。
4、遍歷訂閱者集合,然后根據傳入的訂閱者做比較,判斷是否是同一訂閱者。如果是則移除,反之。
參考:http://www.cnblogs.com/all88/archive/2016/03/30/5338412.html