前面對EventBus 的簡單實用寫了一篇,相信大家都會使用,如果使用的還不熟,或者不夠6,可以花2分鐘瞄一眼:http://www.itdecent.cn/p/321108571fd0
源碼分析準備工作
原因:好多同事同學最近出去面試都問,其實我很早前看過了,現(xiàn)在記不住了,而且自己使用的東西最好知道所以然
版本:EventBus 3.0
源碼結構圖

獲取實例并注冊
EventBus.getDefault().register(this);
1.getDefault()的源碼是怎樣的,代碼如下,很明顯是單例模式!雙重鎖校驗,并且實例使用了關鍵字volatile 修飾,保證線程安全,簡單說一下volatile,只作用于變量,讓變量在各個線程可見的。不能保證原子性,比如i++ ,分3步,從內存讀出i ,然后i++ ,然后在寫到內存,這也是內存模型的知識,也就是 可能在第一步還沒搞完,就讀回去了,這個一般區(qū)別synchronized ,synchronized 有可能會造成線程阻塞,不多說了,回到本質。
static volatile EventBus defaultInstance;
。。。
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
2.我們繼續(xù)看下Eventbus的構造方法:
/**
* Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
* central bus, consider {@link #getDefault()}.
*/
public EventBus() {
this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
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;
}
構造使用的public 修飾?不怕我創(chuàng)建對象嗎,我在看源碼時就比較好奇,發(fā)現(xiàn)他的注釋:創(chuàng)建事件總線實例都在他的范圍內,推薦我們用中央bus考慮使用單例!也就是每一個EventBus都是獨立地、處理它們自己的事件,因此可以存在多個EventBus而通過getDefault()方法獲取的實例,則是它已經(jīng)幫我們構建好的EventBus,是單例,無論在什么時候通過這個方法獲取的實例都是同一個實例。
進行了一堆成員變量的初始化操作,重點看下這幾個關鍵的成員變量,看下等會他們干什么的
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
private final Map<Class<?>, Object> stickyEvents;
subscriptionsByEventType
以event(即事件類)為key,以訂閱列表(Subscription)為value,事件發(fā)送之后,在這里尋找訂閱者
而Subscription又是一個CopyOnWriteArrayList,這是一個線程安全的容器 ,Subscription是一個封裝類,封裝了訂閱者、訂閱方法這兩個類。它的構造如下:
Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
this.subscriber = subscriber;
this.subscriberMethod = subscriberMethod;
active = true;
}
typesBySubscriber
以訂閱者類為key,以event事件類為value,在進行register或unregister操作的時候,會操作這個hashmap
stickyEvents
保存的是粘性事件
接下來實例化了三個Poster,分別是mainThreadPoster、backgroundPoster、asyncPoster等,這三個Poster是用來處理粘性事件的,然后使用建造者模式對
EventBusBuilder,它的一系列方法用于配置EventBus的屬性,使用getDefault()方法獲取的實例,會有著默認的配置,上面說過,EventBus的構造方法是公有的,所以我們可以通過給EventBusBuilder設置不同的屬性,進而獲取有著不同功能的EventBus。
我們通過建造者模式來手動創(chuàng)建一個EventBus,而不是使用getDefault()方法:
EventBus eventBus = EventBus.builder()
.eventInheritance(false) //默認地,EventBus會考慮事件的超類,即事件如果繼承自超類,那么該超類也會作為事件發(fā)送給訂閱者如果設置為false,則EventBus只會考慮事件類本身
.sendNoSubscriberEvent(true)
.skipMethodVerificationFor(MainActivity.class)
.build();
注冊
EventBus的創(chuàng)建,接下來,我們繼續(xù)講它的注冊過程。要想使一個類成為訂閱者,那么這個類必須有一個訂閱方法,以@Subscribe注解標記的方法,接著調用register()方法來進行注冊
1.注冊: 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);
}
}
}
獲取了訂閱者類的class,接著交給SubscriberMethodFinder.findSubscriberMethods()處理,返回結果保存在List<SubscriberMethod>中,由此可推測通過上面的方法把訂閱方法找出來了,并保存在集合中,那么我們直接看這個方
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
....
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
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這個ConcurrentHashMap 里面獲取,而這個map 存放的是key :類。value 就是所有的訂閱方法放在list中,如果獲取到就返回這個訂閱方法的list 沒有緩存,繼續(xù)往下走,通過EventBus 的構造可以知道,這個標志位。ignoreGennerratedIndex 默認false 就是在建造者初始化時候,一般會調用findUsingInfo方法:
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);
}
上面用到了FindState這個內部類來保存訂閱者類的信息,我們看看它的內部結構
static class FindState {
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
final StringBuilder methodKeyBuilder = new StringBuilder(128);
Class<?> subscriberClass;
Class<?> clazz;
boolean skipSuperClasses;
SubscriberInfo subscriberInfo;
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
....
該內部類保存了訂閱者及其訂閱方法的信息,用Map一一對應進行保存,接著利用initForSubscriber進行初始化,這里subscriberInfo初始化為null ,所以,findUsingInfo方法中會調用findUsingReflectionInSingleClass(findState)
在這個方法中利用反射的方式,對訂閱者類進行掃描,找出訂閱方法,并用上面的Map進行保存,我們來看這個方法 逐一判斷訂閱者類是否存在訂閱方法,如果符合要求,調用findState.checkAdd(method, eventType)返回true的時候,才會把方法保存在findState的subscriberMethods內。而SubscriberMethod則是用于保存訂閱方法的一個類
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");
}
}
}
checkAdd()做了什么:
boolean checkAdd(Method method, Class<?> eventType) {
// 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
// Usually a subscriber doesn't have methods listening to the same event type.
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;
} else {
if (existing instanceof Method) {
if (!checkAddWithMethodSignature((Method) existing, eventType)) {
// Paranoia check
throw new IllegalStateException();
}
// Put any non-Method object to "consume" the existing Method
anyMethodByEventType.put(eventType, this);
}
return checkAddWithMethodSignature(method, eventType);
}
}
這里包含兩重檢驗,第一層檢驗是判斷eventType的類型,而第二次檢驗是判斷方法的完整簽名。首先通過anyMethodByEventType.put(eventType, method) 將eventType以及method放進anyMethodByEventType這個Map中(上面提到),同時該put方法會返回同一個key的上一個value值,所以如果之前沒有別的方法訂閱了該事件,那么existing應該為null,可以直接返回true;否則為某一個訂閱方法的實例,要進行下一步的判斷。接著往下走,會調用checkAddWithMethodSignature()方法
private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());
String methodKey = methodKeyBuilder.toString();
Class<?> methodClass = method.getDeclaringClass();
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
// Only add if not already found in a sub class
return true;
} else {
// Revert the put, old class is further down the class hierarchy
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}
}
首先獲取了當前方法的methodKey、methodClass等,并賦值給subscriberClassByMethodKey,如果方法簽名相同,那么返回舊值給methodClassOld,接著是一個if判斷,判斷methodClassOld是否為空,由于第一次調用該方法的時候methodClassOld肯定是null,此時就可以直接返回true了。但是,后面還有一個判斷即methodClassOld.isAssignableFrom(methodClass),這個的意思是:methodClassOld是否是methodClass的父類或者同一個類。如果這兩個條件都不滿足,則會返回false,那么當前方法就不會添加為訂閱方法了
checkAdd和checkAddWithMethodSignature方法的源碼,那么這兩個方法到底有什么作用呢?從這兩個方法的邏輯來看,第一層判斷根據(jù)eventType來判斷是否有多個方法訂閱該事件,而第二層判斷根據(jù)完整的方法簽名(包括方法名字以及參數(shù)名字)來判斷。
第一種情況:比如一個類有多個訂閱方法,方法名不同,但它們的參數(shù)類型都是相同的(雖然一般不這樣寫,但不排除這樣的可能),那么遍歷這些方法的時候,會多次調用到checkAdd方法,由于existing不為null,那么會進而調用checkAddWithMethodSignature方法,但是由于每個方法的名字都不同,因此methodClassOld會一直為null,因此都會返回true。也就是說,允許一個類有多個參數(shù)相同的訂閱方法。
第二種情況:類B繼承自類A,而每個類都是有相同訂閱方法,換句話說,類B的訂閱方法繼承并重寫自類A,它們都有著一樣的方法簽名。方法的遍歷會從子類開始,即B類,在checkAddWithMethodSignature方法中,methodClassOld為null,那么B類的訂閱方法會被添加到列表中。接著,向上找到類A的訂閱方法,由于methodClassOld不為null而且顯然類B不是類A的父類,methodClassOld.isAssignableFrom(methodClass)也會返回false,那么會返回false。也就是說,子類繼承并重寫了父類的訂閱方法,那么只會把子類的訂閱方法添加到訂閱者列表,父類的方法會忽略
讓我們回到findUsingReflectionInSingleClass方法,當遍歷完當前類的所有方法后,會回到findUsingInfo方法,接著會執(zhí)行最后一行代碼,即return getMethodsAndRelease(findState);那么我們繼續(xù)
SubscriberMethodFinder#getMethodsAndRelease方法
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
//從findState獲取subscriberMethods,放進新的ArrayList
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
//把findState回收
findState.recycle();
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
通過該方法,把subscriberMethods不斷逐層返回,直到返回EventBus#register()方法,最后開始遍歷每一個訂閱方法,并調用subscribe(subscriber, subscriberMethod)方法,那么,我們繼續(xù)來看EventBus#subscribe方法
subscribe
方法內,主要是實現(xiàn)訂閱方法與事件直接的關聯(lián),即注冊,即放進我們上面提到關鍵的幾個Map中:subscriptionsByEventType、typesBySubscriber、stickyEvents
// 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();
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) {
// 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);
}
}
}
訂閱方法中,將訂閱類和訂閱方法,封裝成一個Subscription 對象,再據(jù)事件類型獲取特定的 Subscription,如果為null,說明該subscriber尚未注冊該事件 如果不為null,并且包含了這個subscription 那么說明該subscriber已經(jīng)注冊了該事件,拋出異常
根據(jù)優(yōu)先級來設置放進subscriptions的位置,優(yōu)先級高的會先被通知
根據(jù)subscriber(訂閱者)來獲取它的所有訂閱事件
注冊流程基本分析完畢,而關于最后的粘性事件的處理,這里暫時不說,下面會詳細進行講述。可以看出,整個注冊流程非常地長,方法的調用棧很深,在各個方法中不斷跳轉,那么為了方便讀者理解,下面給出一個流程圖,讀者可結合該流程圖以及上面的詳解來進行理解。
注銷
與注冊相對應的是注銷,當訂閱者不再需要事件的時候,我們要注銷這個訂閱者,即調用以下代碼:
EventBus.getDefault().unregister(this);
那么我們來分析注銷流程是怎樣實現(xiàn)的,首先查看EventBus#unregister:
unregister
public synchronized void unregister(Object subscriber) {
//根據(jù)當前的訂閱者來獲取它所訂閱的所有事件
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍歷所有訂閱的事件
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//從typesBySubscriber中移除該訂閱者
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
上面調用了EventBus#unsubscribeByEventType,把訂閱者以及事件作為參數(shù)傳遞了進去,那么應該是解除兩者的聯(lián)系。
unsubscribeByEventType
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根據(jù)事件類型從subscriptionsByEventType中獲取相應的 subscriptions 集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
//遍歷所有的subscriptions,逐一移除
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
可以看到,上面兩個方法的邏輯是非常清楚的,都是從typesBySubscriber或subscriptionsByEventType移除相應與訂閱者有關的信息,注銷流程相對于注冊流程簡單了很多,其實注冊流程主要邏輯集中于怎樣找到訂閱方法上
發(fā)送事件
接下來,我們分析發(fā)送事件的流程,一般地,發(fā)送一個事件調用以下代碼:
EventBus.getDefault().post(new MessageEvent("Hello !....."));`
我們來看看EventBus#post方法。
public void post(Object event) {
//1、 獲取一個postingState
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
//將事件加入隊列中
eventQueue.add(event);
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");
}
try {
//只要隊列不為空,就不斷從隊列中獲取事件進行分發(fā)
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
首先是獲取一個PostingThreadState,那么PostingThreadState是什么呢?我們來看看它的類結構:
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
可以看出,該PostingThreadState主要是封裝了當前線程的信息,以及訂閱者、訂閱事件等。那么怎么得到這個PostingThreadState呢?讓我們回到post()方法再通過currentPostingThreadState.get()來獲取PostingThreadState。那么currentPostingThreadState又是什么呢?
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
來 currentPostingThreadState是一個ThreadLocal,而ThreadLocal是每個線程獨享的,其數(shù)據(jù)別的線程是不能訪問的,因此是線程安全的。我們再次回到Post()方法,繼續(xù)往下走,是一個while循環(huán),這里不斷地從隊列中取出事件,并且分發(fā)出去,調用的是EventBus#postSingleEvent方法
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//該eventInheritance上面有提到,默認為true,即EventBus會考慮事件的繼承樹
//如果事件繼承自父類,那么父類也會作為事件被發(fā)送
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));
}
}
}
從上面的邏輯來看,對于一個事件,默認地會搜索出它的父類,并且把父類也作為事件之一發(fā)送給訂閱者,接著調用了EventBus#postSingleEventForEventType,把事件、postingState、事件的類傳遞進去,那么我們來看看這個方法
postSingleEventForEventType
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//從subscriptionsByEventType獲取響應的subscriptions
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
//發(fā)送事件
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
}
//...
}
return true;
}
return false;
}
接著,進一步調用了EventBus#postToSubscription,可以發(fā)現(xiàn),這里把訂閱列表作為參數(shù)傳遞了進去,顯然,訂閱列表內部保存了訂閱者以及訂閱方法,那么可以猜測,這里應該是通過反射的方式來調用訂閱方法。具體怎樣的話,我們看源碼。
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 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);
}
}
首先獲取threadMode,即訂閱方法運行的線程,如果是POSTING,那么直接調用invokeSubscriber()方法即可,如果是MAIN,則要判斷當前線程是否是MAIN線程,如果是也是直接調用invokeSubscriber()方法,否則會交給mainThreadPoster來處理,其他情況相類似。這里會用到三個Poster,由于粘性事件也會用到這三個Poster,因此我把它放到下面來專門講述。而EventBus#invokeSubscriber的實現(xiàn)也很簡單,主要實現(xiàn)了利用反射的方式來調用訂閱方法,這樣就實現(xiàn)了事件發(fā)送給訂閱者,訂閱者調用訂閱方法這一過程。如下所示:
invokeSubscriber
void invokeSubscriber(Subscription subscription, Object event) {
try {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
}
//...
}
粘性事件的發(fā)送及接收分析
粘性事件與一般的事件不同,粘性事件是先發(fā)送出去,然后讓后面注冊的訂閱者能夠收到該事件。粘性事件的發(fā)送是通過EventBus#postSticky()方法進行發(fā)送的,我們來看它的源碼:
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
把該事件放進了 stickyEvents這個map中,接著調用了post()方法,那么流程和上面分析的一樣了,只不過是找不到相應的subscriber來處理這個事件罷了。那么為什么當注冊訂閱者的時候可以馬上接收到匹配的事件呢?還記得上面的EventBus#subscribe方法里面有一段是專門處理粘性事件的代碼嗎?即:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//以上省略...
//下面是對粘性事件的處理
if (subscriberMethod.sticky) {
//從EventBusBuilder可知,eventInheritance默認為true.
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();
//如果訂閱者訂閱的事件類型與當前的粘性事件類型相同,那么把該事件分發(fā)給這個訂閱者
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
//根據(jù)eventType,從stickyEvents列表中獲取特定的事件
Object stickyEvent = stickyEvents.get(eventType);
//分發(fā)事件
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
上面的邏輯很清晰,EventBus并不知道當前的訂閱者對應了哪個粘性事件,因此需要全部遍歷一次,找到匹配的粘性事件后,會調用EventBus#checkPostStickyEventToSubscription方法:
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
if (stickyEvent != null) {
// If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
// --> Strange corner case, which we don't take care of here.
postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
}
}
接著,又回到了postToSubscription方法了,無論對于普通事件或者粘性事件,都會根據(jù)threadMode來選擇對應的線程來執(zhí)行訂閱方法,而切換線程的關鍵所在就是mainThreadPoster、backgroundPoster和asyncPoster這三個Poster。
HandlerPoster
我們首先看mainThreadPoster,它的類型是HandlerPoster繼承自Handler:
final class HandlerPoster extends Handler {
//PendingPostQueue隊列,待發(fā)送的post隊列
private final PendingPostQueue queue;
//規(guī)定最大的運行時間,因為運行在主線程,不能阻塞主線程
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
//省略...
}
可以看到,該handler內部有一個PendingPostQueue,這是一個隊列,保存了PendingPost,即待發(fā)送的post,該PendingPost封裝了event和subscription,方便在線程中進行信息的交互。在postToSubscription方法中,當前線程如果不是主線程的時候,會調用HandlerPoster#enqueue方法:
void enqueue(Subscription subscription, Object event) {
//將subscription和event打包成一個PendingPost
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
//入隊列
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
//發(fā)送消息,在主線程運行
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
首先會從PendingPostPool中獲取一個可用的PendingPost,接著把該PendingPost放進PendingPostQueue,發(fā)送消息,那么由于該HandlerPoster在初始化的時候獲取了UI線程的Looper,所以它的handleMessage()方法運行在UI線程:
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
//不斷從隊列中取出pendingPost
while (true) {
//省略...
eventBus.invokeSubscriber(pendingPost);
//..
}
} finally {
handlerActive = rescheduled;
}
}
里面調用到了EventBus#invokeSubscriber方法,在這個方法里面,將PendingPost解包,進行正常的事件分發(fā),這上面都說過了,就不展開說了。
BackgroundPoster
BackgroundPoster繼承自Runnable,與HandlerPoster相似的,它內部都有PendingPostQueue這個隊列,當調用到它的enqueue的時候,會將subscription和event打包成PendingPost:
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
//如果后臺線程還未運行,則先運行
if (!executorRunning) {
executorRunning = true;
//會調用run()方法
eventBus.getExecutorService().execute(this);
}
}
}
該方法通過Executor來運行run()方法,run()方法內部也是調用到了EventBus#invokeSubscriber方法。
AsyncPoster
與BackgroundPoster類似,它也是一個Runnable,實現(xiàn)原理與BackgroundPoster大致相同,但有一個不同之處,就是它內部不用判斷之前是否已經(jīng)有一條線程已經(jīng)在運行了,它每次post事件都會使用新的一條線程
其他
整個EventBus是基于觀察者模式而構建的,而上面的調用觀察者的方法則是觀察者模式的核心所在。
觀察者模式:定義了對象之間的一對多依賴,當一個對象改變狀態(tài)時,它的所有依賴者都會收到通知并自動更新。
從整個EventBus可以看出,事件是被觀察者,訂閱者類是觀察者,當事件出現(xiàn)或者發(fā)送變更的時候,會通過EventBus通知觀察者,使得觀察者的訂閱方法能夠被自動調用。當然了,這與一般的觀察者模式有所不同?;叵胛覀兯眠^的觀察者模式,我們會讓事件實現(xiàn)一個接口或者直接繼承自Java內置的Observerable類,同時在事件內部還持有一個列表,保存所有已注冊的觀察者,而事件類還有一個方法用于通知觀察者的。那么從單一職責原則的角度來說,這個事件類所做的事情太多啦!既要記住有哪些觀察者,又要等到時機成熟的時候通知觀察者,又或者有別的自身的方法。這樣的話,一兩件事件類還好,但如果對于每一個事件類,每一個新的不同的需求,都要實現(xiàn)相同的操作的話,這是非常繁瑣而且低效率的。因此,EventBus就充當了中介的角色,把事件的很多責任抽離出來,使得事件自身不需要實現(xiàn)任何東西,別的都交給EventBus來操作就可以