上一篇中我們講解了EventBus的使用,傳送門(mén):http://www.itdecent.cn/p/1e624bf9144d
這篇我們從源碼出發(fā)一步一步解析EventBus實(shí)現(xiàn)原理。
這里先列出一個(gè)大綱,接下來(lái)會(huì)大致根據(jù)這個(gè)大綱一步一步深入剖析:
1.獲取EventBus實(shí)例;
2.注冊(cè)訂閱者;
3.書(shū)寫(xiě)接收訂閱事件的方法;
4.發(fā)送事件給訂閱者;
5.注銷(xiāo);
1.獲取EventBus實(shí)例
1)EventBus mEventBus = EventBus.getDefault();
2)EventBus eventBus = EventBus.builder()
.logNoSubscriberMessages(false)
.sendNoSubscriberEvent(false)
.build();
1)跟著源碼進(jìn)去:
/**
* Convenience singleton for apps using a process-wide EventBus instance.
* 雙重檢查
*/
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
/**
* Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use acentral bus, consider {@link #getDefault()}.
* 創(chuàng)建一個(gè)新的 EventBus 實(shí)例,每個(gè)實(shí)例在 events 事件被發(fā)送的時(shí)候都是一個(gè)單獨(dú)的領(lǐng)域,為了使用一個(gè) 事件總線(xiàn),考慮用 getDefault() 構(gòu)建。
*/
public EventBus() {
this(DEFAULT_BUILDER);
}
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
單例模式,后面我會(huì)單獨(dú)抽出一篇來(lái)說(shuō),這里略過(guò)。
這里來(lái)看看EventBus的成員變量及構(gòu)造函數(shù):
- 成員變量:
static volatile EventBus defaultInstance; // 單例采用 volatile 修飾符,會(huì)降低性能,但能保證EventBus每次取值都是從主內(nèi)存中讀取
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
// 發(fā)送 post 事件的 map 緩存
private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();
// key 為事件類(lèi)型,value為封裝訂閱者和訂閱方法的對(duì)象的集合
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// key為訂閱者,value為eventType的List集合,用來(lái)存放訂閱者中的事件類(lèi)型
private final Map<Object, List<Class<?>>> typesBySubscriber;
//key為 eventType(事件類(lèi)型對(duì)象的字節(jié)碼),value為發(fā)送的事件對(duì)象
private final Map<Class<?>, Object> stickyEvents; // 黏性事件
// currentPostingThreadState
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
// @Nullable
private final MainThreadSupport mainThreadSupport; // 用于線(xiàn)程間調(diào)度
// @Nullable 主線(xiàn)程中的 poster
private final Poster mainThreadPoster;
// 后臺(tái)線(xiàn)程中的 poster
private final BackgroundPoster backgroundPoster;
// 異步線(xiàn)程中的 poster
private final AsyncPoster asyncPoster;
private final SubscriberMethodFinder subscriberMethodFinder; // 對(duì)已經(jīng)注解過(guò)的Method的查找器
private final ExecutorService executorService; // 線(xiàn)程池 Executors.newCachedThreadPool()
private final boolean throwSubscriberException; // 是否需要拋出SubscriberException
private final boolean logSubscriberExceptions; // 當(dāng)調(diào)用事件處理函數(shù)發(fā)生異常是否需要打印Log
private final boolean logNoSubscriberMessages; // 當(dāng)沒(méi)有訂閱者訂閱這個(gè)消息的時(shí)候是否打印Log
private final boolean sendSubscriberExceptionEvent; // 當(dāng)調(diào)用事件處理函數(shù),如果異常,是否需要發(fā)送Subscriber這個(gè)事件
private final boolean sendNoSubscriberEvent; // 當(dāng)沒(méi)有事件處理函數(shù)時(shí),對(duì)事件處理是否需要發(fā)送sendNoSubscriberEvent這個(gè)標(biāo)志
private final boolean eventInheritance; // 與Event有繼承關(guān)系的類(lèi)是否都需要發(fā)送
private final int indexCount; // 用于記錄event生成索引
private final Logger logger;
PS:
ThreadLocal是線(xiàn)程內(nèi)部的存儲(chǔ)類(lèi),通過(guò)它我們可以在指定的線(xiàn)程中存儲(chǔ)數(shù)據(jù),存儲(chǔ)完只能在指定的線(xiàn)程中獲取到數(shù)據(jù),其他線(xiàn)程就無(wú)法獲取到該線(xiàn)程的數(shù)據(jù)。
- 構(gòu)造函數(shù):
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
// 用于線(xiàn)程間調(diào)度
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
// 用于記錄event生成索引
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
// 對(duì)已經(jīng)注解過(guò)的Method的查找器,會(huì)對(duì)所設(shè)定過(guò) @Subscriber 注解的的方法查找相應(yīng)的Event
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
// 當(dāng)調(diào)用事件處理函數(shù)發(fā)生異常是否需要打印Log
logSubscriberExceptions = builder.logSubscriberExceptions;
// 當(dāng)沒(méi)有訂閱者訂閱這個(gè)消息的時(shí)候是否打印Log
logNoSubscriberMessages = builder.logNoSubscriberMessages;
// 當(dāng)調(diào)用事件處理函數(shù),如果異常,是否需要發(fā)送Subscriber這個(gè)事件
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
// 當(dāng)沒(méi)有事件處理函數(shù)時(shí),對(duì)事件處理是否需要發(fā)送sendNoSubscriberEvent這個(gè)標(biāo)志
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
// 是否需要拋出SubscriberException
throwSubscriberException = builder.throwSubscriberException;
// 與Event有繼承關(guān)系的類(lèi)是否都需要發(fā)送
eventInheritance = builder.eventInheritance;
// 線(xiàn)程池 Executors.newCachedThreadPool()
executorService = builder.executorService;
}
2)跟著源碼進(jìn)去
public class EventBus {
public static EventBusBuilder builder() {
return new EventBusBuilder();
}
}
public class EventBusBuilder {
/**
* Builds an EventBus based on the current configuration.
* 基于當(dāng)前配置生成事件總線(xiàn)
*/
public EventBus build() {
return new EventBus(this);
}
}
可以看到這兩種方法都是通過(guò)EventBusBuilder構(gòu)造出來(lái)的。
- EventBusBuilder:
package org.greenrobot.eventbus;
import android.os.Looper;
import org.greenrobot.eventbus.meta.SubscriberInfoIndex;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* Creates EventBus instances with custom parameters and also allows to install a custom default EventBus instance.
* 使用自定義參數(shù)創(chuàng)建EventBus實(shí)例,并允許安裝自定義默認(rèn)EventBus實(shí)例
* Create a new builder using {@link EventBus#builder()}.
*/
public class EventBusBuilder {
// 這個(gè)就是我們的線(xiàn)程池了,異步任務(wù),后臺(tái)任務(wù)就要靠它來(lái)執(zhí)行了
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
boolean logSubscriberExceptions = true; //訂閱者異常日志
boolean logNoSubscriberMessages = true; //不要訂閱者消息日志
boolean sendSubscriberExceptionEvent = true; //是否發(fā)送訂閱者異常
boolean sendNoSubscriberEvent = true; //是否發(fā)送無(wú)訂閱者異常
boolean throwSubscriberException; // 是否拋出訂閱者異常
boolean eventInheritance = true; // 是否繼承事件
boolean ignoreGeneratedIndex; // 是否忽略生成的索引
boolean strictMethodVerification; // 是否嚴(yán)格執(zhí)行方法驗(yàn)證
ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE; // 默認(rèn)線(xiàn)程池
List<Class<?>> skipMethodVerificationForClasses; // 需要跳過(guò)執(zhí)行方法驗(yàn)證的類(lèi)
List<SubscriberInfoIndex> subscriberInfoIndexes; // 訂閱者信息索引
Logger logger;
MainThreadSupport mainThreadSupport;
EventBusBuilder() {
}
/**
* Default: true 訂閱者異常日志,默認(rèn)打印
*/
public EventBusBuilder logSubscriberExceptions(boolean logSubscriberExceptions) {
this.logSubscriberExceptions = logSubscriberExceptions;
return this;
}
/**
* Default: true 不要訂閱者消息日志
*/
public EventBusBuilder logNoSubscriberMessages(boolean logNoSubscriberMessages) {
this.logNoSubscriberMessages = logNoSubscriberMessages;
return this;
}
/**
* Default: true 是否發(fā)送訂閱者異常
*/
public EventBusBuilder sendSubscriberExceptionEvent(boolean sendSubscriberExceptionEvent) {
this.sendSubscriberExceptionEvent = sendSubscriberExceptionEvent;
return this;
}
/**
* Default: true 是否發(fā)送無(wú)訂閱者異常
*/
public EventBusBuilder sendNoSubscriberEvent(boolean sendNoSubscriberEvent) {
this.sendNoSubscriberEvent = sendNoSubscriberEvent;
return this;
}
/**
* Fails if an subscriber throws an exception (default: false).
* Tip: Use this with BuildConfig.DEBUG to let the app crash in DEBUG mode (only). This way, you won't miss
* exceptions during development.
* 使用buildconfig.debug可以使應(yīng)用程序在調(diào)試模式下崩潰(僅限)。這樣,您就不會(huì)錯(cuò)過(guò)開(kāi)發(fā)過(guò)程中的異常。
*
* 是否拋出訂閱者異常 默認(rèn)為 false,可以在debug情況下設(shè)置為 true 進(jìn)行調(diào)試
*/
public EventBusBuilder throwSubscriberException(boolean throwSubscriberException) {
this.throwSubscriberException = throwSubscriberException;
return this;
}
/**
* By default, EventBus considers the event class hierarchy (subscribers to super classes will be notified).
* Switching this feature off will improve posting of events. For simple event classes extending Object directly,
* we measured a speed up of 20% for event posting. For more complex event hierarchies, the speed up should be
* >20%.
* 默認(rèn)情況下,EventBus考慮事件類(lèi)層次結(jié)構(gòu)(將通知父類(lèi)的訂戶(hù))。
* 關(guān)閉此功能將改進(jìn)事件發(fā)布。
* 對(duì)于直接擴(kuò)展對(duì)象的簡(jiǎn)單事件類(lèi),我們測(cè)量到事件發(fā)布的速度提高了20%。對(duì)于更復(fù)雜的事件層次結(jié)構(gòu),速度應(yīng)大于20%
* <p/>
* However, keep in mind that event posting usually consumes just a small proportion of CPU time inside an app,
* unless it is posting at high rates, e.g. hundreds/thousands of events per second.
* 但是,請(qǐng)記住,事件發(fā)布通常只占用應(yīng)用程序內(nèi)部CPU時(shí)間的一小部分,除非它以高速率發(fā)布,例如每秒數(shù)百/數(shù)千個(gè)事件
*
* 是否繼承事件,把這個(gè)功能關(guān)閉可以提高效率,默認(rèn)為 true
*/
public EventBusBuilder eventInheritance(boolean eventInheritance) {
this.eventInheritance = eventInheritance;
return this;
}
/**
* Provide a custom thread pool to EventBus used for async and background event delivery. This is an advanced
* setting to that can break things: ensure the given ExecutorService won't get stuck to avoid undefined behavior.
* 為用于異步和后臺(tái)事件傳遞的事件總線(xiàn)提供自定義線(xiàn)程池。
* 這是一個(gè)高級(jí)設(shè)置,可以打斷一些事件:確保給定的ExecutorService不會(huì)被卡住以避免未定義的行為
*/
public EventBusBuilder executorService(ExecutorService executorService) {
this.executorService = executorService;
return this;
}
/**
* Method name verification is done for methods starting with onEvent to avoid typos; using this method you can
* exclude subscriber classes from this check. Also disables checks for method modifiers (public, not static nor
* abstract).
* 方法名驗(yàn)證是對(duì)以O(shè)nEvent開(kāi)頭的方法進(jìn)行的,以避免出現(xiàn)錯(cuò)誤;使用此方法,可以從該檢查中排除訂閱服務(wù)器類(lèi)。
* 還禁用對(duì)方法修飾符(公共、非靜態(tài)或抽象)的檢查
*/
public EventBusBuilder skipMethodVerificationFor(Class<?> clazz) {
if (skipMethodVerificationForClasses == null) {
skipMethodVerificationForClasses = new ArrayList<>();
}
skipMethodVerificationForClasses.add(clazz);
return this;
}
/**
* Forces the use of reflection even if there's a generated index (default: false).
* 強(qiáng)制使用反射,即使存在生成的索引(默認(rèn)值:false)。
* 使用索引可以大大提高效率
*/
public EventBusBuilder ignoreGeneratedIndex(boolean ignoreGeneratedIndex) {
this.ignoreGeneratedIndex = ignoreGeneratedIndex;
return this;
}
/**
* Enables strict method verification (default: false).
* 啟用嚴(yán)格的方法驗(yàn)證(默認(rèn)值:false)
*/
public EventBusBuilder strictMethodVerification(boolean strictMethodVerification) {
this.strictMethodVerification = strictMethodVerification;
return this;
}
/**
* Adds an index generated by EventBus' annotation preprocessor.
* 添加由EventBus的批注預(yù)處理器生成的索引,可以添加多個(gè)索引
*/
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if (subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
}
/**
* Set a specific log handler for all EventBus logging. 為所有事件總線(xiàn)日志記錄設(shè)置特定的日志處理程序。
* <p/>
* By default all logging is via {@link android.util.Log} but if you want to use EventBus
* outside the Android environment then you will need to provide another log target.
* 默認(rèn)情況下,所有日志記錄都是通過(guò) android.util.log進(jìn)行的,但如果您想在android環(huán)境之外使用eventbus,則需要提供另一個(gè)日志目標(biāo)。
*/
public EventBusBuilder logger(Logger logger) {
this.logger = logger;
return this;
}
Logger getLogger() {
if (logger != null) {
return logger;
} else {
// also check main looper to see if we have "good" Android classes (not Stubs etc.)
return Logger.AndroidLogger.isAndroidLogAvailable() && getAndroidMainLooperOrNull() != null
? new Logger.AndroidLogger("EventBus") :
new Logger.SystemOutLogger();
}
}
MainThreadSupport getMainThreadSupport() {
if (mainThreadSupport != null) {
return mainThreadSupport;
} else if (Logger.AndroidLogger.isAndroidLogAvailable()) {
Object looperOrNull = getAndroidMainLooperOrNull();
return looperOrNull == null ? null :
new MainThreadSupport.AndroidHandlerMainThreadSupport((Looper) looperOrNull);
} else {
return null;
}
}
Object getAndroidMainLooperOrNull() {
try {
return Looper.getMainLooper();
} catch (RuntimeException e) {
// Not really a functional Android (e.g. "Stub!" maven dependencies)
return null;
}
}
/**
* Installs the default EventBus returned by {@link EventBus#getDefault()} using this builders' values. Must be
* done only once before the first usage of the default EventBus.
* 使用此生成器的值安裝 eventbus getdefault()返回的默認(rèn)eventbus。在第一次使用默認(rèn)事件總線(xiàn)之前只能執(zhí)行一次
* 所以在 Application 中執(zhí)行
* @throws EventBusException if there's already a default EventBus instance in place
* 如果已經(jīng)有了一個(gè)默認(rèn)的eventbus實(shí)例,就拋出異常
*/
public EventBus installDefaultEventBus() {
synchronized (EventBus.class) {
if (EventBus.defaultInstance != null) {
throw new EventBusException("Default instance already exists." +
" It may be only set once before it's used the first time to ensure consistent behavior.");
}
EventBus.defaultInstance = build();
return EventBus.defaultInstance;
}
}
/**
* Builds an EventBus based on the current configuration.
* 基于當(dāng)前配置生成事件總線(xiàn)
*/
public EventBus build() {
return new EventBus(this);
}
}
從上面可以看出通過(guò) EventBusBuilder 這個(gè)類(lèi)可以構(gòu)建出我們想要的EventBus。
注意點(diǎn):installDefaultEventBus()方法的調(diào)用,使用這個(gè)方法生成的 EventBus,在第一次使用默認(rèn)事件總線(xiàn)之前只能執(zhí)行一次,所以在 Application 中執(zhí)行,如果已經(jīng)有了一個(gè)默認(rèn)的eventbus實(shí)例,就拋出異常。
2.注冊(cè)訂閱者
EventBus eventBus = EventBus.builder().build();
eventBus.register(this);
- register方法:
/**
* 注冊(cè)給定的訂閱服務(wù)器以接收事件。一旦訂戶(hù)對(duì)接收事件不再感興趣,他們必須調(diào)用 unregister(object)。
* 訂閱服務(wù)器具有必須由 subscribe 注釋的事件處理方法。 subscribe注釋還允許配置,如 threadMode 和優(yōu)先級(jí)。
*
* 傳進(jìn)來(lái)的是訂閱者 subscriber
*/
public void register(Object subscriber) {
// 通過(guò)反射獲取到訂閱者的對(duì)象
Class<?> subscriberClass = subscriber.getClass();
// 通過(guò)Class對(duì)象找到對(duì)應(yīng)的訂閱者方法集合
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
// 遍歷訂閱者方法集合,將訂閱者和訂閱者放方法想成訂閱關(guān)系
synchronized (this) {
// 迭代每個(gè) Subscribe 方法,調(diào)用 subscribe() 傳入 subscriber(訂閱者) 和 subscriberMethod(訂閱方法) 完成訂閱,
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
- private final SubscriberMethodFinder subscriberMethodFinder; // 對(duì)已經(jīng)注解過(guò)的Method的查找器。
- findSubscriberMethods方法:
// 訂閱方法的緩存,key為訂閱者對(duì)象,value為訂閱者對(duì)象所有的訂閱方法是一個(gè)List集合
private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
/**
* 訂閱方法查找
* @param subscriberClass 訂閱者對(duì)象
* @return 返回訂閱者 所有的訂閱方法 是一個(gè)List集合
*/
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 首先在 METHOD_CACHE 中查找該 Event 對(duì)應(yīng)的訂閱者集合是否已經(jīng)存在,如果有直接返回
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// 根據(jù)訂閱者類(lèi) subscriberClass 查找相應(yīng)的訂閱方法
if (ignoreGeneratedIndex) { // 是否忽略生成 index 默認(rèn)為 false,當(dāng)為 true 時(shí),表示以反射的方式獲取訂閱者中的訂閱方法
subscriberMethods = findUsingReflection(subscriberClass); // 通過(guò)反射獲取
} else {
// 通過(guò) SubscriberIndex 方式獲取
subscriberMethods = findUsingInfo(subscriberClass);
}
// 若訂閱者中沒(méi)有訂閱方法,則拋異常
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); // 把訂閱方法集合 List 存到緩存中
return subscriberMethods;
}
}
- findUsingReflection() 通過(guò)反射獲取訂閱方法集合 *** start ***
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
// 創(chuàng)建并初始化 FindState 對(duì)象
FindState findState = prepareFindState();
// findState 與 subscriberClass 關(guān)聯(lián)
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 使用反射的方式獲取單個(gè)類(lèi)的訂閱方法
findUsingReflectionInSingleClass(findState);
// 使 findState.clazz 指向父類(lèi)的 Class,繼續(xù)獲取
findState.moveToSuperclass();
}
// 返回訂閱者及其父類(lèi)的訂閱方法 List,并釋放資源
return getMethodsAndRelease(findState);
}
- prepareFindState()方法:
class SubscriberMethodFinder {
private static final int POOL_SIZE = 4;
private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
}
// 通過(guò) prepareFindState 獲取到 FindState 對(duì)象
private FindState prepareFindState() {
// 找到 FIND_STATE_POOL 對(duì)象池
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
// 當(dāng)找到了對(duì)應(yīng)的FindState
FindState state = FIND_STATE_POOL[i];
if (state != null) { // FindState 非空表示已經(jīng)找到
FIND_STATE_POOL[i] = null; // 清空找到的這個(gè)FindState,為了下一次能接著復(fù)用這個(gè)FIND_STATE_POOL池
return state; // 返回該 FindState
}
}
}
// 如果依然沒(méi)找到,則創(chuàng)建一個(gè)新的 FindState
return new FindState();
}
- FindState這是EventBus的一個(gè)靜態(tài)內(nèi)部類(lèi):
// FindState 封裝了所有的訂閱者和訂閱方法的集合
static class FindState {
// 保存所有訂閱方法
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
// 事件類(lèi)型為Key,訂閱方法為Value
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
// 訂閱方法為Key,訂閱者的Class對(duì)象為Value
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
final StringBuilder methodKeyBuilder = new StringBuilder(128);
Class<?> subscriberClass;
Class<?> clazz;
boolean skipSuperClasses;
SubscriberInfo subscriberInfo;
// findState 與 subscriberClass 關(guān)聯(lián)
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
void recycle() {
subscriberMethods.clear();
anyMethodByEventType.clear();
subscriberClassByMethodKey.clear();
methodKeyBuilder.setLength(0);
subscriberClass = null;
clazz = null;
skipSuperClasses = false;
subscriberInfo = null;
}
/**
* EventBus 不僅僅獲取當(dāng)前類(lèi)的訂閱方法,還會(huì)獲取它所有父類(lèi)的訂閱方法。
*
* 在 EventBus 中,一個(gè)訂閱者包括這個(gè)訂閱者的所有父類(lèi)和子類(lèi),不會(huì)有多個(gè)方法相同的去接收同一個(gè)事件.
* 但是有可能出現(xiàn)這樣一種情況,子類(lèi)去訂閱了該事件,父類(lèi)也去訂閱了該事件。
* 當(dāng)出現(xiàn)這種情況,EventBus 如何判斷?通過(guò)調(diào)用 checkAddWithMethodSignature() 方法,根據(jù)方法簽名來(lái)檢查
*/
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.
// put()方法執(zhí)行之后,返回的是之前put的值
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);
}
// 根據(jù)方法簽名來(lái)檢查
return checkAddWithMethodSignature(method, eventType);
}
}
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();
// put方法返回的是put之前的對(duì)象
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
// 如果methodClassOld不存在或者是methodClassOld的父類(lèi)的話(huà),則表明是它的父類(lèi),直接返回true。
// 否則,就表明在它的子類(lèi)中也找到了相應(yīng)的訂閱,執(zhí)行的 put 操作是一個(gè) revert 操作,put 進(jìn)去的是 methodClassOld,而不是 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
// 這里是一個(gè)revert操作,所以如果找到了它的子類(lèi)也訂閱了該方法,則不允許父類(lèi)和子類(lèi)都同時(shí)訂閱該事件,put 的是之前的那個(gè) methodClassOld,就是將以前的那個(gè) methodClassOld 存入 HashMap 去覆蓋相同的訂閱者。
// 不允許出現(xiàn)一個(gè)訂閱者有多個(gè)相同方法訂閱同一個(gè)事件
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}
}
// 使 findState.clazz 指向父類(lèi)的 Class,繼續(xù)獲取
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;
}
}
}
}
- findUsingReflectionInSingleClass方法:
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(); // 通過(guò)反射獲取到所有方法
} 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();
// 忽略非 public 和 static 的方法
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 獲取訂閱方法的所有參數(shù)
Class<?>[] parameterTypes = method.getParameterTypes();
// 訂閱方法只能有一個(gè)參數(shù),否則忽略
if (parameterTypes.length == 1) {
// 獲取有 Subscribe 的注解
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
// 獲取第一個(gè)參數(shù)
Class<?> eventType = parameterTypes[0];
// 檢查 eventType 決定是否訂閱,通常訂閱者不能有多個(gè) eventType 相同的訂閱方法
if (findState.checkAdd(method, eventType)) {
// 獲取線(xiàn)程模式
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 添加訂閱方法進(jìn) List
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");
}
}
}
- getMethodsAndRelease方法: 返回訂閱者及其父類(lèi)的訂閱方法 List,并釋放資源
// 保存所有訂閱方法
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
private static final int POOL_SIZE = 4;
private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
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;
}
上面這一堆方法都是講的從反射獲取訂閱者的方法。 end
下面這個(gè)方法表示從索引獲?。?/strong>
- 通過(guò) SubscriberIndex 方式獲取
findUsingInfo方法:
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
// 通過(guò) prepareFindState 獲取到 FindState(保存找到的注解過(guò)的方法的狀態(tài))
FindState findState = prepareFindState();
// findState 與 subscriberClass 關(guān)聯(lián)
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 獲取訂閱者信息
// 通過(guò) SubscriberIndex 獲取 findState.clazz 對(duì)應(yīng)的 SubscriberInfo
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
// 逐個(gè)添加進(jìn) findState.subscriberMethods
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
// 使用反射的方式獲取單個(gè)類(lèi)的訂閱方法
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
這個(gè)方法里面的涉及到的方法在上面講發(fā)射的時(shí)候都有了,這里就不重復(fù)了。引入一個(gè)新的接口:
- SubscriberInfo:
/**
* Base class for generated index classes created by annotation processing.
* 由批注處理創(chuàng)建的已生成索引類(lèi)的基類(lèi)
*/
public interface SubscriberInfo {
Class<?> getSubscriberClass();
SubscriberMethod[] getSubscriberMethods();
SubscriberInfo getSuperSubscriberInfo();
boolean shouldCheckSuperclass();
}
- AbstractSubscriberInfo是SubscriberInfo 實(shí)現(xiàn)的抽象類(lèi)
/**
* Base class for generated subscriber meta info classes created by annotation processing.
* 由批注處理創(chuàng)建的已生成訂閱服務(wù)器元信息類(lèi)的基類(lèi)
*/
public abstract class AbstractSubscriberInfo implements SubscriberInfo {
private final Class subscriberClass;
private final Class<? extends SubscriberInfo> superSubscriberInfoClass;
private final boolean shouldCheckSuperclass;
protected AbstractSubscriberInfo(Class subscriberClass, Class<? extends SubscriberInfo> superSubscriberInfoClass,
boolean shouldCheckSuperclass) {
this.subscriberClass = subscriberClass;
this.superSubscriberInfoClass = superSubscriberInfoClass;
this.shouldCheckSuperclass = shouldCheckSuperclass;
}
@Override
public Class getSubscriberClass() {
return subscriberClass;
}
@Override
public SubscriberInfo getSuperSubscriberInfo() {
if (superSubscriberInfoClass == null) {
return null;
}
try {
return superSubscriberInfoClass.newInstance();
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
@Override
public boolean shouldCheckSuperclass() {
return shouldCheckSuperclass;
}
protected SubscriberMethod createSubscriberMethod(String methodName, Class<?> eventType) {
return createSubscriberMethod(methodName, eventType, ThreadMode.POSTING, 0, false);
}
protected SubscriberMethod createSubscriberMethod(String methodName, Class<?> eventType, ThreadMode threadMode) {
return createSubscriberMethod(methodName, eventType, threadMode, 0, false);
}
protected SubscriberMethod createSubscriberMethod(String methodName, Class<?> eventType, ThreadMode threadMode,
int priority, boolean sticky) {
try {
Method method = subscriberClass.getDeclaredMethod(methodName, eventType);
return new SubscriberMethod(method, eventType, threadMode, priority, sticky);
} catch (NoSuchMethodException e) {
throw new EventBusException("Could not find subscriber method in " + subscriberClass +
". Maybe a missing ProGuard rule?", e);
}
}
}
- SimpleSubscriberInfo最終繼承上面的抽象類(lèi)
/**
* Uses {@link SubscriberMethodInfo} objects to create {@link SubscriberMethod} objects on demand.
* 使用 SubscriberMethodInfo 對(duì)象根據(jù)需要?jiǎng)?chuàng)建 SubscriberMethod 對(duì)象。
*/
public class SimpleSubscriberInfo extends AbstractSubscriberInfo {
private final SubscriberMethodInfo[] methodInfos;
public SimpleSubscriberInfo(Class subscriberClass, boolean shouldCheckSuperclass, SubscriberMethodInfo[] methodInfos) {
super(subscriberClass, null, shouldCheckSuperclass);
this.methodInfos = methodInfos;
}
@Override
public synchronized SubscriberMethod[] getSubscriberMethods() {
int length = methodInfos.length;
SubscriberMethod[] methods = new SubscriberMethod[length];
for (int i = 0; i < length; i++) {
SubscriberMethodInfo info = methodInfos[i];
methods[i] = createSubscriberMethod(info.methodName, info.eventType, info.threadMode,
info.priority, info.sticky);
}
return methods;
}
}
- 最后就是要?jiǎng)?chuàng)建出的 SubscriberMethod 對(duì)象
/**
* Used internally by EventBus and generated subscriber indexes.
*
* 封裝了EventBus中的參數(shù),就是一個(gè)EventBus訂閱方法包裝類(lèi)
*/
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;
}
@Override
public boolean equals(Object other) {
if (other == this) {
return true;
} else if (other instanceof SubscriberMethod) {
checkMethodString();
SubscriberMethod otherSubscriberMethod = (SubscriberMethod) other;
otherSubscriberMethod.checkMethodString();
// Don't use method.equals because of http://code.google.com/p/android/issues/detail?id=7811#c6
return methodString.equals(otherSubscriberMethod.methodString);
} else {
return false;
}
}
private synchronized void checkMethodString() {
if (methodString == null) {
// Method.toString has more overhead, just take relevant parts of the method
StringBuilder builder = new StringBuilder(64);
builder.append(method.getDeclaringClass().getName());
builder.append('#').append(method.getName());
builder.append('(').append(eventType.getName());
methodString = builder.toString();
}
}
@Override
public int hashCode() {
return method.hashCode();
}
}
到這里索引也分析完了,索引的具體使用:http://www.itdecent.cn/p/1e624bf9144d
接下來(lái)注冊(cè)的關(guān)鍵性一步:將訂閱者和訂閱者放方法形成訂閱關(guān)系
subscribe方法:
// Must be called in synchronized block 必須組同步塊中調(diào)用
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
// 創(chuàng)建 Subscription 封裝訂閱者和訂閱方法信息
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 可并發(fā)讀寫(xiě)的 ArrayList(CopyOnWriteArrayList)),key為 EventType,value為 Subscriptions
// 根據(jù)事件類(lèi)型從 subscriptionsByEventType 這個(gè) Map 中獲取 Subscription 集合
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 如果為 null,表示還沒(méi)有(注冊(cè))訂閱過(guò),創(chuàng)建并 put 進(jìn) Map
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
// 若subscriptions中已經(jīng)包含newSubscription,表示該newSubscription已經(jīng)被訂閱過(guò),拋出異常
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
// 按照優(yōu)先級(jí)插入subscriptions
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;
}
}
// key為訂閱者,value為eventType,用來(lái)存放訂閱者中的事件類(lèi)型
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
// 將EventType放入subscribedEvents的集合中
subscribedEvents.add(eventType);
//判斷是否為Sticky事件
if (subscriberMethod.sticky) {
//判斷是否設(shè)置了事件繼承
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>).
// 獲取到所有Sticky事件的Set集合
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
//遍歷所有Sticky事件
for (Map.Entry<Class<?>, Object> entry : entries) {
Class<?> candidateEventType = entry.getKey();
//判斷當(dāng)前事件類(lèi)型是否為黏性事件或者其子類(lèi)
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
// 執(zhí)行設(shè)置了 sticky 模式的訂閱方法
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
- 這里涉及到一個(gè)類(lèi)Subscription:
// 封裝訂閱者和訂閱方法信息
final class Subscription {
final Object subscriber; // 訂閱者對(duì)象
final SubscriberMethod subscriberMethod; // 訂閱的方法
}
- 檢查有沒(méi)有post粘性的事件
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.
// 如果訂閱者試圖中止事件,它將失?。ㄔ诎l(fā)布狀態(tài)下不跟蹤事件)情況,我們?cè)谶@里不處理。
postToSubscription(newSubscription, stickyEvent, isMainThread());
}
}
- postToSubscription方法: 這里調(diào)用主要是為了檢查沒(méi)有注冊(cè)之前是否發(fā)送了黏性事件
/**
* 訂閱者五種線(xiàn)程模式的特點(diǎn)對(duì)應(yīng)的就是以上代碼,簡(jiǎn)單來(lái)講就是訂閱者指定了在哪個(gè)線(xiàn)程訂閱事件,無(wú)論發(fā)布者在哪個(gè)線(xiàn)程,它都會(huì)將事件發(fā)布到訂閱者指定的線(xiàn)程
* @param subscription
* @param event
* @param isMainThread
*/
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
// 訂閱線(xiàn)程跟隨發(fā)布線(xiàn)程,EventBus 默認(rèn)的訂閱方式
case POSTING:
invokeSubscriber(subscription, event); // 訂閱線(xiàn)程和發(fā)布線(xiàn)程相同,直接訂閱
break;
// 訂閱線(xiàn)程為主線(xiàn)程
case MAIN:
if (isMainThread) { // 如果 post是在 UI 線(xiàn)程,直接調(diào)用 invokeSubscriber
invokeSubscriber(subscription, event);
} else {
// 如果不在 UI 線(xiàn)程,用 mainThreadPoster 進(jìn)行調(diào)度,即上文講述的 HandlerPoster 的 Handler 異步處理,將訂閱線(xiàn)程切換到主線(xiàn)程訂閱
mainThreadPoster.enqueue(subscription, event);
}
break;
// 訂閱線(xiàn)程為主線(xiàn)程
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;
// 訂閱線(xiàn)程為后臺(tái)線(xiàn)程
case BACKGROUND:
// 如果在 UI 線(xiàn)程,則將 subscription 添加到后臺(tái)線(xiàn)程的線(xiàn)程池
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
// 不在UI線(xiàn)程,直接分發(fā)
invokeSubscriber(subscription, event);
}
break;
// 訂閱線(xiàn)程為異步線(xiàn)程
case ASYNC:
// 使用線(xiàn)程池線(xiàn)程訂閱
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
到這里注冊(cè)流程就分析完了,下面貼上一張整體流程圖:

3.書(shū)寫(xiě)接收訂閱事件的方法
@Subscribe(threadMode = ThreadMode.POSTING,sticky = false,priority = 4)
public void onEventThread(EventCenter eventCenter){
switch (eventCenter.getEventType()) {
case EventType.ONE:
Log.e("MainActivity", eventCenter.getEventType());
break;
default:
break;
}
// EventBus.getDefault().cancelEventDelivery(eventCenter);
}
- 這里主要涉及到注解及黏性事件。
注解:
@Documented // 命名為 java doc 文檔
@Retention(RetentionPolicy.RUNTIME) // 指定在運(yùn)行時(shí)有效,即在運(yùn)行時(shí)能保持這個(gè) Subscribe
@Target({ElementType.METHOD}) // 指定類(lèi)型為 METHOD,表名用來(lái)描述方法
public @interface Subscribe {
// 指定線(xiàn)程模式,可以指定在 Subscribe 中接收的 Event 所處的線(xiàn)程
ThreadMode threadMode() default ThreadMode.POSTING; // 訂閱線(xiàn)程的模式,默認(rèn)從哪個(gè)線(xiàn)程發(fā)送,就從哪個(gè)線(xiàn)程訂閱
/**
* If true, delivers the most recent sticky event (posted with
* {@link EventBus#postSticky(Object)}) to this subscriber (if event available).
* 粘性事件是事件消費(fèi)者在事件發(fā)布之后才注冊(cè),依然能接收到該事件的特殊類(lèi)型。
*/
boolean sticky() default false;
/** Subscriber priority to influence the order of event delivery.
* Within the same delivery thread ({@link ThreadMode}), higher priority subscribers will receive events before
* others with a lower priority. The default priority is 0. Note: the priority does *NOT* affect the order of
* delivery among subscribers with different {@link ThreadMode}s!
* 數(shù)值越高優(yōu)先級(jí)越大,越先接收事件
* */
int priority() default 0;
}
總結(jié):
- 粘性事件是事件消費(fèi)者在事件發(fā)布之后才注冊(cè),依然能接收到該事件的特殊類(lèi)型
- 任何時(shí)候在任何一個(gè)訂閱了該事件的訂閱者中的任何地方,都可以通 EventBus.getDefault().getStickyEvent(MyEvent.class)來(lái)取得該類(lèi)型事件的最后一次緩存。
- 優(yōu)先級(jí)priority數(shù)值越高優(yōu)先級(jí)越大,越先接收事件
線(xiàn)程模式ThreadMode
/**
* Each subscriber method has a thread mode, which determines in which thread the method is to be called by EventBus.
* EventBus takes care of threading independently from the posting thread.
*
* 每個(gè)訂閱服務(wù)器方法都有一個(gè)線(xiàn)程模式,該模式?jīng)Q定EventBus在哪個(gè)線(xiàn)程中調(diào)用該方法。EventBus獨(dú)立于發(fā)布線(xiàn)程來(lái)處理線(xiàn)程。
*
* @see EventBus#register(Object)
* @author Markus
*/
public enum ThreadMode {
/**
* Subscriber will be called directly in the same thread, which is posting the event. This is the default. Event delivery
* implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for
* simple tasks that are known to complete in a very short time without requiring the main thread. Event handlers
* using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
*
* 訂閱服務(wù)器將直接在發(fā)布事件的同一線(xiàn)程中調(diào)用。這是默認(rèn)設(shè)置。事件傳遞意味著開(kāi)銷(xiāo)最小,因?yàn)樗耆苊饬司€(xiàn)程切換。
* 因此,對(duì)于已知在非常短的時(shí)間內(nèi)完成而不需要主線(xiàn)程的簡(jiǎn)單任務(wù),建議使用這種模式。
* 使用此模式的事件處理程序必須快速返回,以避免阻塞可能是主線(xiàn)程的發(fā)布線(xiàn)程。
*/
POSTING, // EventBus 默認(rèn)的線(xiàn)程模式 就是訂閱的線(xiàn)程和發(fā)送事件的線(xiàn)程為同一線(xiàn)程
/**
* On Android, subscriber will be called in Android's main thread (UI thread). If the posting thread is
* the main thread, subscriber methods will be called directly, blocking the posting thread. Otherwise the event
* is queued for delivery (non-blocking). Subscribers using this mode must return quickly to avoid blocking the main thread.
* If not on Android, behaves the same as {@link #POSTING}.
*
*
* 在A(yíng)ndroid上,用戶(hù)將在A(yíng)ndroid的主線(xiàn)程(UI線(xiàn)程)中被調(diào)用。
* 如果發(fā)布線(xiàn)程是主線(xiàn)程,則將直接調(diào)用訂閱方法,從而阻塞發(fā)布線(xiàn)程。否則,事件將排隊(duì)等待傳遞(非阻塞)。
* 使用此模式的訂閱必須快速返回,以避免阻塞主線(xiàn)程。如果不在A(yíng)ndroid上,其行為與 POSTING 發(fā)布相同。
* 因?yàn)榘沧恐骶€(xiàn)程阻塞會(huì)發(fā)生 ANR 異常
*/
MAIN, // 主線(xiàn)程
/**
* On Android, subscriber will be called in Android's main thread (UI thread). Different from {@link #MAIN},
* the event will always be queued for delivery. This ensures that the post call is non-blocking.
*
* 在A(yíng)ndroid上,用戶(hù)將在A(yíng)ndroid的主線(xiàn)程(UI線(xiàn)程)中被調(diào)用。與 MAIN 不同,事件將始終排隊(duì)等待傳遞。這樣可以確保后調(diào)用不阻塞
*/
MAIN_ORDERED, // 主線(xiàn)程
/**
* On Android, subscriber will be called in a background thread. If posting thread is not the main thread, subscriber methods
* will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
* background thread, that will deliver all its events sequentially. Subscribers using this mode should try to
* return quickly to avoid blocking the background thread. If not on Android, always uses a background thread.
*
* 在A(yíng)ndroid上,訂閱將在后臺(tái)線(xiàn)程中被調(diào)用。如果發(fā)布線(xiàn)程不是主線(xiàn)程,則將直接在發(fā)布線(xiàn)程中調(diào)用訂閱方法。
* 如果發(fā)布線(xiàn)程是主線(xiàn)程,那么 eventBus 使用單個(gè)后臺(tái)線(xiàn)程,該線(xiàn)程將按順序傳遞其所有事件。
* 使用此模式的訂閱應(yīng)嘗試快速返回,以避免阻塞后臺(tái)線(xiàn)程。如果不在A(yíng)ndroid上,則始終使用后臺(tái)線(xiàn)程。
*
*/
BACKGROUND, // 后臺(tái)線(xiàn)程
/**
* Subscriber will be called in a separate thread. This is always independent from the posting thread and the
* main thread. Posting events never wait for subscriber methods using this mode. Subscriber methods should
* use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
* of long running asynchronous subscriber methods at the same time to limit the number of concurrent threads. EventBus
* uses a thread pool to efficiently reuse threads from completed asynchronous subscriber notifications.
*
* 將在單獨(dú)的線(xiàn)程中調(diào)用訂閱服務(wù)器。這始終獨(dú)立于發(fā)布線(xiàn)程和主線(xiàn)程。
* 發(fā)布事件從不等待使用此模式的訂閱方法。
* 如果訂閱服務(wù)器方法的執(zhí)行可能需要一些時(shí)間,例如用于網(wǎng)絡(luò)訪(fǎng)問(wèn),則應(yīng)使用此模式。
* 避免同時(shí)觸發(fā)大量長(zhǎng)時(shí)間運(yùn)行的異步訂閱服務(wù)器方法,以限制并發(fā)線(xiàn)程的數(shù)量。
* EventBus使用線(xiàn)程池來(lái)有效地重用已完成的異步訂閱服務(wù)器通知中的線(xiàn)程。
*
*/
ASYNC // 異步線(xiàn)程
}
4.發(fā)送事件給訂閱者
// 發(fā)送黏性事件
EventBus.getDefault().postSticky(new EventCenter<>(EventType.ONE));
// 發(fā)送普通事件
EventBus.getDefault().post(new EventCenter<>(EventType.ONE));
- postSticky方法:
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 如果訂閱者希望立即刪除,則應(yīng)在放入后發(fā)布
post(event);
}
- post方法:
/**
* Posts the given event to the event bus.
* 將給定事件發(fā)布到事件總線(xiàn)
*/
public void post(Object event) {
// 獲取當(dāng)前線(xiàn)程的 posting 狀態(tài)
PostingThreadState postingState = currentPostingThreadState.get();
// 獲取當(dāng)前事件隊(duì)列
List<Object> eventQueue = postingState.eventQueue;
// 將事件添加進(jìn)當(dāng)前線(xiàn)程的事件隊(duì)列
eventQueue.add(event);
// 判斷是否正在posting(發(fā)送))
if (!postingState.isPosting) {
postingState.isMainThread = isMainThread();
postingState.isPosting = true;
// 如果已經(jīng)取消,則拋出異常
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
while (!eventQueue.isEmpty()) { // 循環(huán)從事件隊(duì)列中取出事件
// 發(fā)送事件
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
// 狀態(tài)復(fù)原
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
- 發(fā)送事件的線(xiàn)程封裝類(lèi) PostingThreadState
/**
* For ThreadLocal, much faster to set (and get multiple values).
*
* 發(fā)送事件的線(xiàn)程封裝類(lèi)
*/
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<>(); // 事件隊(duì)列
boolean isPosting; // 是否正在 posting
boolean isMainThread; // 是否為主線(xiàn)程
Subscription subscription;
Object event;
boolean canceled; // 是否已經(jīng)取消
}
- postSingleEvent 發(fā)送方法:
/**
* 發(fā)送事件
*
* EventBus 用 ThreadLocal 存儲(chǔ)每個(gè)線(xiàn)程的 PostingThreadState,一個(gè)存儲(chǔ)了事件發(fā)布狀態(tài)的類(lèi),
* 當(dāng) post 一個(gè)事件時(shí),添加到事件隊(duì)列末尾,等待前面的事件發(fā)布完畢后再拿出來(lái)發(fā)布,
* 這里看事件發(fā)布的關(guān)鍵代碼postSingleEvent()
*/
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) { // 處理繼承事件
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass); // 查找所有相關(guān)父類(lèi)及接口
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz); // 將事件作為特定的類(lèi)型事件進(jìn)行發(fā)送
}
} else {
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
if (!subscriptionFound) { // 沒(méi)有找到注冊(cè)的處理函數(shù),即還沒(méi)有注冊(cè)能夠處理該事件的函數(shù),(異常處理)
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)); // 如果沒(méi)有人和訂閱者訂閱發(fā)送 NoSubscriberEvent
}
}
}
- lookupAllEventTypes方法:
/**
* Looks up all Class objects including super classes and interfaces. Should also work for interfaces.
* 看看涉及到lookupAllEventTypes,就是查找到發(fā)生事件的所有相關(guān)類(lèi)(父類(lèi))
*/
private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
synchronized (eventTypesCache) {
List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class<?> clazz = eventClass;
while (clazz != null) {
eventTypes.add(clazz);
addInterfaces(eventTypes, clazz.getInterfaces());
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
}
/**
* Recurses through super interfaces. 遍歷父類(lèi)接口
*/
static void addInterfaces(List<Class<?>> eventTypes, Class<?>[] interfaces) {
for (Class<?> interfaceClass : interfaces) {
if (!eventTypes.contains(interfaceClass)) {
eventTypes.add(interfaceClass);
addInterfaces(eventTypes, interfaceClass.getInterfaces()); // 遞歸
}
}
}
- postSingleEventForEventType方法:
// 進(jìn)一步深入的發(fā)送事件函數(shù):
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass); // 查找是否存在處理eventClass的注冊(cè)處理函數(shù) (查找該事件的所有訂閱者)
}
if (subscriptions != null && !subscriptions.isEmpty()) { // 有對(duì)應(yīng)的處理函數(shù)
for (Subscription subscription : subscriptions) { // 依次分發(fā)
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false; // 用于確定是否需要繼續(xù)分發(fā),也許已經(jīng)被攔截不需要分發(fā)了
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;
}
最終走了這個(gè)方法postToSubscription()進(jìn)行事件發(fā)送
/**
* 訂閱者五種線(xiàn)程模式的特點(diǎn)對(duì)應(yīng)的就是以上代碼,簡(jiǎn)單來(lái)講就是訂閱者指定了在哪個(gè)線(xiàn)程訂閱事件,無(wú)論發(fā)布者在哪個(gè)線(xiàn)程,它都會(huì)將事件發(fā)布到訂閱者指定的線(xiàn)程
* @param subscription
* @param event
* @param isMainThread
*/
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
// 訂閱線(xiàn)程跟隨發(fā)布線(xiàn)程,EventBus 默認(rèn)的訂閱方式
case POSTING:
invokeSubscriber(subscription, event); // 訂閱線(xiàn)程和發(fā)布線(xiàn)程相同,直接訂閱
break;
// 訂閱線(xiàn)程為主線(xiàn)程
case MAIN:
if (isMainThread) { // 如果 post是在 UI 線(xiàn)程,直接調(diào)用 invokeSubscriber
invokeSubscriber(subscription, event);
} else {
// 如果不在 UI 線(xiàn)程,用 mainThreadPoster 進(jìn)行調(diào)度,即上文講述的 HandlerPoster 的 Handler 異步處理,將訂閱線(xiàn)程切換到主線(xiàn)程訂閱
mainThreadPoster.enqueue(subscription, event);
}
break;
// 訂閱線(xiàn)程為主線(xiàn)程
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;
// 訂閱線(xiàn)程為后臺(tái)線(xiàn)程
case BACKGROUND:
// 如果在 UI 線(xiàn)程,則將 subscription 添加到后臺(tái)線(xiàn)程的線(xiàn)程池
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
// 不在UI線(xiàn)程,直接分發(fā)
invokeSubscriber(subscription, event);
}
break;
// 訂閱線(xiàn)程為異步線(xiàn)程
case ASYNC:
// 使用線(xiàn)程池線(xiàn)程訂閱
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
到這里事件發(fā)送也分析完了,老規(guī)矩附上流程圖:

由于篇幅所限,剩下的內(nèi)容傳送門(mén):http://www.itdecent.cn/p/f61b8e7da6b4