一、基本原理
我們在開發(fā)過程中Activity、Fragment、Service等之間的交互方式有廣播、回調(diào)或者AIDL等。但是使用時都比較繁瑣,EventBus使用簡單只需注冊、使用Subscribe注解方法在需要傳遞數(shù)據(jù)處post數(shù)據(jù)就可以了、并且可以傳遞Model類型數(shù)據(jù)。EventBus是基于觀察者模式,EventBus相當(dāng)于被觀察者,我們的Activity、fragment等就是觀察者,在EventBus里面有一個subscriberByEventType Map集合,當(dāng)我們post事件時都會遍歷這個集合通知觀察者處理事件。在分析源碼時可能不會糾結(jié)于太多細(xì)節(jié)的地方,主要是分析整個流程即可。
二、源碼解析
1.初始化
Eventbus.getDefault.register(),EventBus.getDefault()使用單例獲取到defaultInstance的EventBus對象。保證每次獲取EventBus對象都是唯一的。
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
在EventBus的默認(rèn)構(gòu)造方法會調(diào)用 EventBus(EventBusBuilder builder)這個構(gòu)造方法初始化數(shù)據(jù)
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
//在register會將當(dāng)前對象跟方法put進(jìn)來,post方法時會遍歷
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
//主線程回調(diào)
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
//在子線程回調(diào)
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;
}
subscriptionsByEventType這個HashMap集合key是當(dāng)前注冊對象,value是subscription的CopyOnWriteArrayList集合。subscription類是每個對象對應(yīng)subscriber注解的方法。typesBySubscriber這個HashMap集合key是當(dāng)前注冊對象,value是該類注冊的所有方法。
2.register(注冊)
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
findSubscriberMethods找出一個SubscriberMethod的集合,也就是傳進(jìn)來的訂閱者所有的訂閱的方法,接下來遍歷訂閱者的訂閱方法來完成訂閱者的訂閱操作。對于SubscriberMethod(訂閱方法)類中,主要就是用保存訂閱方法的Method對象、線程模式、事件類型、優(yōu)先級、是否是粘性事件等屬性。下面就來看一下findSubscriberMethods方法:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//ignoreGeneratedIndex屬性表示是否忽略注解器生成的MyEventBusIndex
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
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;
}
}
首先會通過METHOD_CACHE緩存獲取,如果不為空直接取緩存的數(shù)據(jù),緩存為空則繼續(xù)往下走。不了解MyEventBusIndex的同學(xué)可以查看【Bugly干貨分享】老司機教你 “飆” EventBus 3這篇文章。<br />ignoreGeneratedIndex默認(rèn)是false,所以會進(jìn)入findUsingInfo(subscriberClass)方法
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//獲取訂閱者信息
findState.subscriberInfo = getSubscriberInfo(findState);
//沒有配置MyEventBusIndex所以subscriberInfo是null
if (findState.subscriberInfo是null != 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);
}
getSubscriberInfo(findState)里面由于沒有添加index索引,所以返回null,最近進(jìn)入 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) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
int modifiers = method.getModifiers();
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");
}
}
}
這里主要是使用了Java的反射跟對注解的解析,首先通過反射拿到對象的所有方法,然后根據(jù)方法的類型、參數(shù)和注解找到訂閱方法。找到訂閱方法后將訂閱信息保存到findState中。<br />獲取到方法列表SubscribMethods后,就是遍歷列表對所有方法進(jìn)行注冊了。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
//通過訂閱者和訂閱方法構(gòu)造一個訂閱事件
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//獲取當(dāng)前訂閱事件的訂閱者Subscription的List集合
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//首次subscriptions list集合為null 則創(chuàng)建新的集合put到map集合
if (subscriptions list集合為null 則創(chuàng)建新的集合put到map集合 == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//如果以及存在newSubscription則報出異常
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
//遍歷訂閱事件集合找到比sunscriptionss priority訂閱事件小的位置,然后插進(jìn)去
//或者就是put到集合最后
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);
}
//將當(dāng)前的訂閱事件添加到subscribedEvents中 typesBySubscriber保存了每個Subscriber對應(yīng)的訂閱事件
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);
}
}
}
訂閱的代碼主要做了兩件事,就是將訂閱事件和訂閱者封裝到subscriptionsByEventType和typesBySubscriber兩個集合中去,subscriptionsByEventType是在post事件時,根據(jù)事件類型EventType獲取到訂閱事件列表List<Subscription>,然后去分發(fā)事件處理事件;typesBySubscriber是在unRegister(this)時,根據(jù)訂閱者找到EventType,又根據(jù)EventType找到訂閱事件,從而對訂閱者進(jìn)行解綁。如果是粘性事件的話立馬投遞執(zhí)行。

3.事件發(fā)送 post
當(dāng)獲取到EventBus對象并注冊以后,可以通過post 發(fā)送事件
public void post(Object event) {
//PostingThreadState保存著事件隊列和當(dāng)前線程狀態(tài)
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);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
從PostingThreadState獲取事件隊列,將事件插入到隊列中,然后遍歷將事件通過postSingleEvent發(fā)送出去。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
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) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
eventInheritance表示是否向上查找事件的父類,它的默認(rèn)值為true,可以通過在EventBusBuilder中來進(jìn)行配置。當(dāng)eventInheritance為true時,則通過lookupAllEventTypes找到所有的父類事件并存在List中,然后通過postSingleEventForEventType方法對事件逐一處理,接下來看看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;
}
同步取出該事件對應(yīng)的Subscription集合并遍歷該集合將事件event和對應(yīng)Subscription傳遞給postingState并調(diào)用postToSubscription方法對事件進(jìn)行處理,接下來看看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);
}
}
取出訂閱方法的線程模式,之后根據(jù)線程模式來分別處理。舉個例子,如果線程模式是MAIN,提交事件的線程是主線程的話則通過反射,直接運行訂閱的方法,如果不是主線程,我們需要mainThreadPoster將我們的訂閱事件入隊列,mainThreadPoster是HandlerPoster類型的繼承自Handler,通過Handler將訂閱方法切換到主線程執(zhí)行。

4.取消訂閱者unRegister
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 {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
根據(jù)訂閱者在typesBySubscriber中獲取到事件列表,然后遍歷事件列表,subscriptionsByEventType獲取到的訂閱事件列表,然后解除事件類型跟改訂閱者的關(guān)系。最后在typesBySubscriber刪除訂閱者的事件列表

三、核心架構(gòu)

利與弊
EventBus好處比較明顯,它能夠解耦和,將業(yè)務(wù)和視圖分離,代碼實現(xiàn)比較容易。而且3.0后,我們可以通過apt預(yù)編譯找到訂閱者,避免了運行期間的反射處理解析,大大提高了效率。當(dāng)然EventBus也會帶來一些隱患和弊端,如果濫用的話會導(dǎo)致邏輯的分散并造成維護起來的困難。另外大量采用EventBus代碼的可讀性也會變差。