在進入主題之前,我們先保持着這樣幾個疑問,EventBus的使用三要素裏,我們爲什麼要去定義事件方法,並且用到了@subscribe()註解? EventBus.getDefault().register(Object)這行代碼到底幹了什麼?發送事件的時候又做了哪些操作?爲什麼要在onDestory()做解除綁定的操作…等等
(一) 註冊: EventBus.getDefault().register(obj)
首先調用EventBus的靜態getDefault()方法返回一個EventBus對象,採用單例實現。
// 靜態的單例
static volatile EventBus defaultInstance;
// 默認的EventBusBuilder對象
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
// 使用了單例的雙重鎖機制
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
// 調用帶參數的構造方法
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;
}
在EventBus(builder)構造方法裏初始化了一些配置信息。
之後調用了EventBus的register(obj)方法,這個方法接收的參數類型是Object。這裏我們分步驟1和步驟2去看看做了哪些操作。
public void register(Object subscriber) {
// 通過反射拿到傳入的obj的Class對象,如果是在MainActivity裏做的註冊操作,
// 那subscriber就是MainActivity對象
Class<?> subscriberClass = subscriber.getClass();
// 步驟1
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
// 步驟2
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
步驟1
List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
首先subscriberMethodFinder
對象是在EventBus帶參數的構造函數裏進行初始化的,從這個findSubscriberMethods()
方法名就可以看出來,步驟1的是去獲取當前註冊的對象裏所有的被@Subscribe
註解的方法集合,那這個List集合的對象SubscriberMethod
又是什麼東東呢? 我們去看一下
/** Used internally by EventBus and generated subscriber indexes. */
public class SubscriberMethod {
final Method method;
final ThreadMode threadMode;
final Class<?> eventType;
final int priority;
final boolean sticky;
/** Used for efficient comparison */
String methodString;
public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
this.method = method;
this.threadMode = threadMode;
this.eventType = eventType;
this.priority = priority;
this.sticky = sticky;
}
...
}
看完這個類裏定義的信息,大概明白了。SubscriberMethod 定義了Method方法名,ThreadMode 線程模型,eventType 事件的class對象,priority是指接收事件的優先級,sticky是指是否是粘性事件,SubscriberMethod 對這些信息做了一個封裝。這些信息在我們處理事件的時候都會用到。
好的,知道了SubscriberMethod 是什麼東東後,我們直接進入findSubscriberMethods(subscriberClass)
方法:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// METHOD_CACHE是事先定義了一個緩存Map,以當前的註冊對象的Class對象爲key,註冊的對象裏所有的被@Subscribe註解的方法集合爲value
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
// 第一次進來的時候,緩存裏面沒有集合,subscriberMethods 爲null
if (subscriberMethods != null) {
return subscriberMethods;
}
// ignoreGeneratedIndex是在SubscriberMethodFinder()的構造函數初始化的,默認值是 false
if (ignoreGeneratedIndex) {
// 通過反射去獲取
subscriberMethods = findUsingReflection(subscriberClass);
} else {
// 通過apt插件生成的代碼。使用subscriber Index生成的SubscriberInfo來獲取訂閱者的事件處理函數,
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;
}
}
這裏利用了享元模式,首先是從緩存中獲取,如果緩存中存在直接返回,這裏使用緩存有一個 好處,比如在MainActivity進行了註冊操作,多次啓動MainActivity,就會直接去緩存中拿數據。如果緩存裏沒有數據,就會根據ignoreGeneratedIndex 這個boolean值去調用不同的方法,ignoreGeneratedIndex 默認爲false。如果此時,獲取到的方法集合還是空的,程序就會拋出異常,提醒用戶被註冊的對象以及他的父類沒有被@Subscribe註解的public方法(這裏插一句,很多時候,如果打正式包的時候EventBus沒有做混淆處理,就會拋出該異常,因爲方法名被混淆處理了,EventBus會找不到),把獲取到的方法集合存入到緩存中去,並且把方法集合return出去。
大致的流程就是這樣,findSubscriberMethods()負責獲取註冊對象的方法集合,優先從緩存中獲取,緩存中不存在,則根據ignoreGeneratedIndex是true或false,如果ignoreGeneratedIndex爲true,則調用findUsingReflection(),如果爲false,則調用findUsingInfo()方法去獲取方法集合
看完這裏,我們知道了一個需要注意的地方就是:調用了EventBus.getDefault().register(this)的類一定要添加@Subscribe註解的訂閱方法,否則app會崩潰!
findUsingInfo():
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
// 這裏採用了享元設計模式
FindState findState = prepareFindState();
// 初始化FindState裏的參數
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對象採用了享元模式
private FindState prepareFindState() {
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
FindState state = FIND_STATE_POOL[i];
if (state != null) {
FIND_STATE_POOL[i] = null;
return state;
}
}
}
return new 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;
}
....
....
}
這裏先獲取了FindState對象,之後調用了 findState.initForSubscriber(subscriberClass)
方法,只是爲了給FindState對象裏的一些信息進行賦值操作。再然後是一個 while循環,循環裏首先調用getSubscriberInfo(findState)
方法,點進去看一下,發現該方法返回null。這裏留一個小疑問,getSubscriberInfo()方法什麼時候不爲null?? 答案留到最後。
private SubscriberInfo getSubscriberInfo(FindState findState) {
// findState.subscriberInfo在初始化的時候置爲null,所以該if 分支不會執行
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
// subscriberInfoIndexes初始化的時候也是null,並沒有賦值
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
所以findUsingInfo()
的while循環裏直接走了else分支:findUsingReflectionInSingleClass(findState)
。
也就是說findUsingInfo()方法的主要邏輯是由findUsingReflectionInSingleClass()方法去完成的(默認情況,不考慮使用apt)
這裏有個細節要看一下:
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();
}
這個while循環什麼時候結束呢?這是我們第一次看EventBus源碼看到這裏比較疑惑的地方,答案就在這個 findState.moveToSuperclass()
裏面:
void moveToSuperclass() {
if (skipSuperClasses) {
clazz = null;
} else {
clazz = clazz.getSuperclass();
String clazzName = clazz.getName();
/** Skip system classes, this just degrades performance. */
if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
clazz = null;
}
}
}
我們可以看到這裏clazz賦值爲它的超類,直到沒有父類爲止,才返回clazz=null
,循環也才終止。也就是說 這個while循環保證了,獲取註解的方法不僅會從當前註冊對象裏去找,也會去從他的父類查找。
好了,繼續分析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) {
// 獲取該方法的修飾符,即public、private等
int modifiers = method.getModifiers();
// 修飾符是public纔會走該分支
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 這裏是獲取該方法的參數類型,String,in
Class<?>[] parameterTypes = method.getParameterTypes();
// 只有一個參數會走該分支
if (parameterTypes.length == 1) {
// 如果該方法被@subscribe註解會走該分支
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
// 獲取傳入的對象的Class
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");
}
}
}
findUsingReflectionInSingleClass()方法首先通過反射去拿到當前註冊對象的所有的方法,然後去進行遍歷,並進行第一次過濾,只針對修飾符是Public的方法,之後進行了第二次過濾,判斷了方法的參數的個數是不是隻有一個,如果滿足,纔去進一步的獲取被@subscribe註解的方法。
然後調用
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,subscribeAnnotation.priority(), subscribeAnnotation.sticky()))
這行代碼,new了一個SubscriberMethod()對象,傳入參數,並添加到 findState.subscriberMethods的集合中去.
static class FindState {
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
}
之後,findUsingInfo()
的getMethodsAndRelease(findState)
方法回去獲取剛剛設置的findState
的subscriberMethods
集合,並把它return出去。代碼如下:
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
// 對subscriberMethods進行了賦值,return出去
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
// 進行了回收
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;
}
步驟1總結:至此,以上就是EventBus獲取一個註冊對象的所有的被@subscribe註解的方法的集合的一個過程。該過程的主要方法流程爲:
(1) subscriberMethodFinder.findSubscriberMethods()
(2) findUsingInfo()
(3) findUsingReflectionInSingleClass()
步驟2
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
通過步驟1,我們已經拿到了註冊對象的所有的被@subscribe註解的方法的集合的。現在我們看看subscribe()都做了哪些 操作。
我們不妨想想,如果我們要去做subscribe()時,我們要考慮哪些問題,第一個問題是,要判斷一下這些方法是不是已經註冊過該事件了要不要考慮方法名是不是相同的問題。第二個問題是一個註冊對象中有多個方法註冊了該事件,我們該怎麼保存這些方法,比如說事件類型是String,一個Activity裏有兩個方法註冊了該事件,分別是onEvent1和onEvent2,那我是不是應該用一個Map集合,以事件類型爲key,把onEvent1和onEvent2放到一個List集合中,把該List集合作爲value。
subscribe()方法:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 拿到事件event類型,比如是String或者自定義的對象
Class<?> eventType = subscriberMethod.eventType;
// Subscription將註冊對象和subscriberMethod 做爲參數傳入
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// subscriptionsByEventType是一個Map集合,key是事件類型,驗證了我上面的猜想
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 如果subscriptions是null,則new出一個CopyOnWriteArrayList,並且往Map集合中添加
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
// 這裏做了if語句判斷,判斷一下List集合中是否存在,存在就拋異常
// 如果不存在?怎麼沒有add操作? 保持疑問
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
以上的操作驗證了我之前的猜想,通過if (subscriptions.contains(newSubscription)) 這個if語句判斷 是否發生了重複註冊,注意這裏重複註冊的含義是 事件類型一致,以及方法名也一致。
接下來我們看看如果一個註冊對象重複註冊了事件Event(方法名不能一致),優先級priority是如何設置的
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
// 這裏判斷subscriberMethod的優先級是否是大於集合中的subscriberMethod的優先級,如果是,把newSubscription插進去
// 這也表明了subscription中priority大的在前,這樣在事件分發時就會先獲取。
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
if語句的條件subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) ,保證了subscription中priority大的在前。同時i == size 這個條件也保證了priority小的也會添加到subscriptions集合中去
緊接着我們看看EventBus是如何處理粘性事件的:
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);
}
}
}
注意以上代碼有四行比較重要的註釋信息。大致的意思是必須考慮eventType所有子類的現有粘性事件,在迭代的過程中,所有的event可能會因爲大量的sticky events變得低效,爲了使得查詢變得高效應該改變數據結構。
isAssignableFrom方法的意思是判斷candidateEventType是不是eventType的子類或者子接口,如果postSticky()的參數是子Event,那麼@Subscribe註解方法中的參數是父Event也可以接收到此消息。
拿到粘性Event後,調用了checkPostStickyEventToSubscription()
方法,改方法內部方法內部調用了postToSubscription()
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());
}
}
步驟2總結:至此,EventBus的註冊操作已經全部分析完了,需要注意的是,粘性事件是在subscribe中進行post的
(二) 發送事件:EventBus.getDefault().post(xxx);
普通Event
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
// 將Event添加到List集合中去
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 {
// 遍歷這個list集合,條件是集合是否是空的
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
首先將當前的 Event添加到eventQueue
中去,並且while循環,處理post每一個Event事件,調用的是 postSingleEvent(eventQueue.remove(0), postingState)
:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
// 獲取Event的Class對象
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
// eventInheritance初始化的時候值爲true,所以會走該分支
if (eventInheritance) {
// 獲取當前的Event的Class對象的所有父類的Class對象集合,優先從緩存裏讀取。
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);
}
...
...
}
這裏lookupAllEventTypes()
方法也是爲了獲取當前的Event的Class對象的所有父類的Class對象集合,優先從緩存裏讀取。之後是 for循環獲取到的Class對象集合,調用postSingleEventForEventType()
方法:
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// subscriptionsByEventType該map是在subscribe()方法中進行了put操作
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
// 進行for循環並調用了postToSubscription()
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;
}
postSingleEventForEventType()
方法,主要是獲取Event的Class對象所對應的一個List集合,集合的對象是Subscription參數。subscriptionsByEventType對象是在subscribe()方法中進行了賦值。for循環CopyOnWriteArrayList集合,並調用postToSubscription()
線程模型
等執行到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);
}
第一個分支:線程模型是POSTING,直接調用了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);
}
}
很明顯的看到,這是基於反射去調用方法,invoke方法接收兩個參數,第一個參數是註冊的對象,第二個參數是事件的Event。
從這裏就可以看出來,POST並沒有去做線程的調度什麼的,事件處理函數的線程跟發佈事件的線程在同一個線程。
第二個分支:線程模型是MAIN 首先判斷了下事件發佈的線程是不是主線程,如果是,執行invokeSubscriber()
方法,invokeSubscriber()
上面已經分析過,如果不是主線程,執行mainThreadPoster.enqueue(subscription, event)
。mainThreadPoster
是繼承自Handler
,從這裏大概可以猜到,這一步是去做線程調度的。/font>
我們看一看mainThreadPoster
的enqueue
做了什麼事:
void enqueue(Subscription subscription, Object event) {
// 封裝了一個PendIngPost
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
// 將PendIngPost壓入隊列
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
// 調用了sendMessage()
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
enqueue()
主要封裝了一個PendingPost
類,並把subscription
和event
作爲參數傳進去,緊接着把PendingPost
壓入到隊列中去,然後sendMessage
發了一條消息。
熟悉Handler機制的同學知道,處理消息是在handleMessage()方法中完成的:
public void handleMessage(Message msg) {
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;
}
}
}
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;
}
}
代碼有點多,我們主要看一下,它接收到消息後,是做了什麼處理。從隊列中取了消息,並且調用了eventBus.invokeSubscriber(pendingPost)
方法,回到EventBus類中。
void invokeSubscriber(PendingPost pendingPost) {
Object event = pendingPost.event;
Subscription subscription = pendingPost.subscription;
PendingPost.releasePendingPost(pendingPost);
if (subscription.active) {
invokeSubscriber(subscription, event);
}
}
該方法內部還是去調用了invokeSubscriber()
方法。
分析完線程模型爲MAIN 的工作流程,不難做出結論,當發佈事件所在的線程是在主線程時,我們不需要做線程調度,直接調用反射方法去執行。如果發佈事件所在的線程不是在主線程,需要使用Handler做線程的調度,並最終調用反射方法去執行
第三個分支:線程模型是BACKGROUND。如果事件發佈的線程是在主線程,執行backgroundPoster.enqueue(subscription, event)
,否則執行invokeSubscriber()
。
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
eventBus.getExecutorService().execute(this);
}
}
}
將PendingPost
對象壓入隊列,然後調用eventBus.getExecutorService().execute(this)
,交給線程池去進行處理,它的處理是在Runnable的run()
中。backgroundPoster
實現了Runable
接口:
@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;
}
}
}
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
最重要的還是eventBus.invokeSubscriber(pendingPost)
這行代碼,上面已經分析過。
第四個分支:線程模型是ASYNC。直接調用 asyncPoster.enqueue(subscription, event)
,asyncPoster
也是實現了Runnable
接口,裏面也是使用的線程池,具體的操作就不分析了,感興趣的可以去看一下源碼,跟上一步操作類似。
(三) 高級用法
EventBus3.0較之前的版本有了一次改造,在3.0之後增加了註解處理器,在程序的編譯時候,就可以根據註解生成相對應的代碼,相對於之前的直接通過運行時反射,大大提高了程序的運行效率,但是在3.0默認的還是通過反射去查找用@Subscribe標註的方法,一般在使用的時候基本都是這個模式。 那我們怎麼配置讓EventBus使用註解器生成的代碼呢? EventBus官網apt介紹
在這裏我們重點提一下 EventBusBuilder類的:
boolean ignoreGeneratedIndex;
List<SubscriberInfoIndex> subscriberInfoIndexes;
subscriberInfoIndexes
變量可以去使用註解處理器生成的代碼。SubscriberInfoIndex
就是一個接口,而註解生成器生成的類也是繼承的它,我們也可以自己去繼承它,定製自己的需求,不需要反射的EventBus。
我們再回過頭來看一下注冊過程的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);
}
我們在前面分析的時候,直接分析的 findUsingReflectionInSingleClass(findState)
方法,因爲getSubscriberInfo()
返回null,那什麼時候getSubscriberInfo()
返回不爲null呢 ? 我們具體看看getSubscriberInfo()
。
private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
// 判斷subscriberInfoIndexes 是否爲null,默認爲null,當我們使用apt插件構建代碼 的時候,可以手動的調用EventBusBuilder的addIndex,將subscriberInfoIndexes 進行賦值。
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
當我們使用apt
插件構建代碼的時候,可以手動的調用EventBusBuilder
的addIndex()
,將subscriberInfoIndexes
進行賦值。這樣subscriberInfoIndexes
就不會爲null,getSubscriberInfo()
方法也就不會爲null。findUsingInfo()
也就不會調用反射去獲取數據,從而提高了性能。