一泄私、構(gòu)建
1抒抬、EventBus實(shí)例創(chuàng)建采用了DCL單例:
static volatile EventBus defaultInstance;
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
2恐似、其構(gòu)造器相關(guān)代碼如下:
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
// 基于事件類型, 訂閱列表構(gòu)成的集合
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
public EventBus() {
this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
// 線程發(fā)送器
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
// 設(shè)置build選項(xiàng)
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;
}
也就是說木缝,采用的是默認(rèn)的建造者EventBusBuilder對(duì)象來構(gòu)建EventBus對(duì)象秃励。
其中初始化的subscriptionsByEventType 氏仗、typesBySubscriber 是兩個(gè)很重要的map集合。
二夺鲜、注冊(cè)
1皆尔、注冊(cè)訂閱者對(duì)象
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
// 獲得訂閱者方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
// 訂閱
subscribe(subscriber, subscriberMethod);
}
}
}
可以看出,subscriberMethodFinder根據(jù)訂閱者Class實(shí)例來獲得subscriberMethod集合币励。SubscriberMethod是對(duì)注冊(cè)方法以及相關(guān)屬性的封裝:
public class SubscriberMethod {
final Method method;
final ThreadMode threadMode;
final Class<?> eventType;
final int priority;
final boolean sticky;
/** Used for efficient comparison */
String methodString;
...
}
到此慷蠕,我們可以聯(lián)想到Method對(duì)象之后應(yīng)該會(huì)執(zhí)行invoke方法,這也是EventBus傳遞消息的根本食呻。ThreadMode是線程模式流炕,我們都知道EventBus可以通過注解來指定執(zhí)行線程。
2仅胞、查找訂閱者方法
// 方法緩存集合每辟,線程安全
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;
}
// 默認(rèn)為false
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 {
// 添加進(jìn)緩存
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
這是一個(gè)獲得數(shù)據(jù)并添加到緩存的過程,ignoreGeneratedIndex是在EventBusBuilder中設(shè)置的干旧,默認(rèn)為false渠欺,也就是說返回的結(jié)果是由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對(duì)象是對(duì)查找狀態(tài)的封裝莱革。調(diào)用initForSubscriber方法后峻堰,findState.clazz為subscriberClass,findState.subscriberInfo為null盅视,故而調(diào)用findUsingReflectionInSingleClass方法捐名,這個(gè)方法是查找功能的具體實(shí)現(xiàn)。
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();
// 必須是public闹击,且不是Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 參數(shù)類型
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");
}
}
}
由上可以看到方法查找的邏輯镶蹋,最終把滿足要求的方法以及相關(guān)參數(shù)封裝起來,添加到 findState.subscriberMethods集合中赏半。
接下來回到findUsingInfo方法中贺归,又調(diào)用了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;
}
}
}
這是一個(gè)把遍歷目標(biāo)轉(zhuǎn)移到父類的方法断箫,skipSuperClasses默認(rèn)為false拂酣。該方法不停的循環(huán),一直到系統(tǒng)類仲义,將clazz對(duì)象設(shè)為null婶熬,從而結(jié)束循環(huán)。
最終返回訂閱方法集合埃撵。
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
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;
}
3赵颅、訂閱關(guān)系確立
之前查找到的訂閱方法集合僅僅是把SubscriberMethod 對(duì)象累積起來,并不能根據(jù)事件類型暂刘,快速得到訂閱對(duì)象(post方法發(fā)送的是事件對(duì)象)饺谬,故而需要遍歷訂閱方法對(duì)象,建立訂閱關(guān)系谣拣。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
// 封裝訂閱對(duì)象募寨、訂閱方法為訂閱關(guān)系
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
// 建立事件類型-訂閱關(guān)系映射
subscriptionsByEventType.put(eventType, subscriptions);
} else {
// 重復(fù)注冊(cè)拋出異常
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) {
// 添加訂閱關(guān)系到集合中
subscriptions.add(i, newSubscription);
break;
}
}
// 根據(jù)訂閱對(duì)象獲得事件類型
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);
}
}
}
由上述方法可得到兩個(gè)集合subscriptionsByEventType、typesBySubscriber森缠,建立了事件類型與訂閱對(duì)象之間的雙重映射绪商。前者用于發(fā)送事件處理,后者用于取消注冊(cè)辅鲸。
三格郁、發(fā)送
1、發(fā)送事件對(duì)象
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
// 未發(fā)送
if (!postingState.isPosting) {
// 判斷當(dāng)前線程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
// 遍歷事件隊(duì)列
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
// 結(jié)束后reset
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
currentPostingThreadState是一個(gè)ThreadLocal對(duì)象独悴,用于存儲(chǔ)當(dāng)前線程的PostingThreadState對(duì)象例书。
final static class PostingThreadState {
// 事件隊(duì)列
final List<Object> eventQueue = new ArrayList<Object>();
// 是否發(fā)送中
boolean isPosting;
// 是否主線程
boolean isMainThread;
// 訂閱關(guān)系
Subscription subscription;
Object event;
boolean canceled;
}
回到post方法,得到事件隊(duì)列后刻炒,將事件添加到隊(duì)列中决采。在事件隊(duì)列不為空的情況下,遍歷調(diào)用postSingleEvent方法坟奥。
2树瞭、單一事件處理
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
// 事件繼承,默認(rèn)為true
if (eventInheritance) {
// 事件對(duì)象的所有父類及實(shí)現(xiàn)接口
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ā)送單一事件會(huì)繼續(xù)遍歷事件的父類與父接口,也就是處理事件繼承晒喷。
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 從集合中根據(jù)事件類型取出訂閱關(guān)系
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 遍歷訂閱關(guān)系(含訂閱對(duì)象與訂閱方法)
for (Subscription subscription : subscriptions) {
// 發(fā)送狀態(tài)讀取訂閱關(guān)系
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
// 根據(jù)不同模式進(jìn)行處理
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;
}
3孝偎、不同模式下處理事件
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
// 發(fā)送事件的線程
case POSTING:
invokeSubscriber(subscription, event);
break;
// 主線程
case MAIN:
// 當(dāng)前為主線程
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);
}
}
可以看出,針對(duì)當(dāng)前線程和目標(biāo)線程凉敲,分別做了處理衣盾。最終調(diào)用invokeSubscriber方法。
void invokeSubscriber(Subscription subscription, Object event) {
try {
// 反射調(diào)用訂閱方法
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
四爷抓、線程變換
1势决、Main發(fā)送器
主要是在HandlerPoster類中進(jìn)行處理
void enqueue(Subscription subscription, Object event) {
// 將訂閱關(guān)系與事件封裝為PendingPost對(duì)象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
// 進(jìn)入PendingPost隊(duì)列
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
// 發(fā)送消息開始執(zhí)行
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
// 消息處理
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
// 出隊(duì)
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
// 隊(duì)列為空
handlerActive = false;
return;
}
}
}
// 反射調(diào)用訂閱方法
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
// 重新調(diào)度
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
2、Background發(fā)送器
使用線程池處理事件
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
主要是在BackgroundPoster類中處理
public void enqueue(Subscription subscription, Object event) {
// 將訂閱關(guān)系與事件封裝為PendingPost對(duì)象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
// 進(jìn)入PendingPost隊(duì)列
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
// 線程池處理
eventBus.getExecutorService().execute(this);
}
}
}
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;
}
}
}
// 反射調(diào)用訂閱方法
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
3蓝撇、Async發(fā)送器
在新建的子線程進(jìn)行處理事件
private final PendingPostQueue queue;
private final EventBus eventBus;
AsyncPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}
@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}