05、Android--EventBus原理解析
EventBus原理
EventBus構造方法
當我們要使用EventBus時,首先會呼叫EventBus.getDefault()來獲取EventBus例項。
public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }
單例模式,採用了雙重檢查模式 (DCL)。接下來檢視 EventBus 的構造方法:
public EventBus() {
this(DEFAULT_BUILDER);
}
這裡DEFAULT_BUILDER是預設的EventBusBuilder,用來構造EventBus:
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
this呼叫了EventBus的另一個構造方法,如下所示:
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; }
通過構造一個EventBusBuilder來對EventBus進行配置,這裡採用了建造者模式。
訂閱者註冊
獲取EventBus後,便可以將訂閱者註冊到EventBus中。下面來看一下register方法:
public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); // findSubscriberMethods方法找出一個SubscriberMethod的集合,也就是傳進來的訂閱者的 // 所有訂閱方法,接下來遍歷訂閱者的訂閱方法來完成訂閱者的註冊操作。 List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }
查詢訂閱者的訂閱方法
register方法做了兩件事:一件事是查詢訂閱者的訂閱方法,另一件事是訂閱者的註冊。
在SubscriberMethod類中,主要用來保 存訂閱方法的Method物件、執行緒模式、事件型別、優先順序、是否是黏性事件等屬性。下面就來檢視findSubscriberMethods方法,如下所示:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
// 從快取中查詢是否有訂閱方法的集合,如果找到了就立馬返回。
if (subscriberMethods != null) {
return subscriberMethods;
}
// 如果快取沒有,則根據ignoreGeneratedIndex屬性的值來選擇採用何種方法來查詢訂閱方法的集合。
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;
}
}
ignoreGeneratedIndex 屬性表示是否忽略註解器生成的 MyEventBusIndex。
我們在專案中經常通過EventBus單例模式來獲取預設的EventBus對 象,也就是ignoreGeneratedIndex為false的情況,這種情況呼叫了findUsingInfo方法:
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
SubscriberMethodFinder.FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 通過 getSubscriberInfo 方法來獲取訂閱者資訊
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
// 呼叫subscriberInfo的getSubscriberMethods方法便可以得 到訂閱方法相關的資訊
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
// 將訂閱方法儲存到findState中
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
// 回收處理並返回訂閱方法的List集合
return getMethodsAndRelease(findState);
}
預設情況下是沒有配置MyEventBusIndex的,因此現在檢視一下findUsingReflectionInSingleClass方法的執行過程,如下所示:
private void findUsingReflectionInSingleClass(SubscriberMethodFinder.FindState findState) {
Method[] methods;
try {
// 通過反射來獲取訂閱者中所有的方法,並根據方法的型別、引數和註解來找到訂閱方法。
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
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");
}
}
}
找到訂閱方法後將訂閱方法的相關資訊儲存到findState中。
訂閱者的註冊過程
在查詢完訂閱者的訂閱方法以後便開始對所有的訂閱方法進行註冊。我們再回到 register方法中,subscribe方法來對訂閱方法進行註冊,如下所示:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
// 根據subscriber(訂閱者)和subscriberMethod(訂閱方法)建立一個Subscription(訂閱物件)
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 根據eventType(事件型別)獲取Subscriptions(訂閱物件集合)
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 如果 Subscriptions為null則重新建立,並將Subscriptions根據eventType儲存在subscriptionsByEventType(Map集合)
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;
}
}
// 通過 subscriber獲取subscribedEvents(事件型別集合)。
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
if (subscriberMethod.sticky) {
if (eventInheritance) {
// 粘性事件的處理
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
for (Map.Entry<Class<?>, Object> entry : entries) {
Class<?> candidateEventType = entry.getKey();
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
subscribe方法主要就是做了兩件事:一件事是將Subscriptions根據eventType封裝到subscriptionsByEventType
中,將subscribedEvents根據subscriber封裝到typesBySubscriber中;第二件事就是對黏性事件的處理。
事件的傳送
在獲取EventBus物件以後,可以通過post方法來進行對事件的提交。post方法的原始碼如下所示:
public void post(Object event) {
// PostingThreadState儲存事件佇列和執行緒狀態資訊
EventBus.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 {
// 處理佇列中的所有事件
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
首先從PostingThreadState物件中取出事件佇列,然後再將當前的事件插入事件佇列。最後將佇列中的
事件依次交由 postSingleEvent 方法進行處理,並移除該事件。之後檢視postSingleEvent方法:
private void postSingleEvent(Object event, EventBus.PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
// eventInheritance表示是否向上查詢事件的父類,預設為true
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));
}
}
}
eventInheritance 表示是否向上查詢事件的父類,它的預設值為 true,可以通過在EventBusBuilder中進行
配置。當eventInheritance為true時,則通過lookupAllEventTypes找到所有的父類事件並存在List中,然後通過
postSingleEventForEventType方法對事件逐一處理。postSingleEventForEventType方法的原始碼如下所示:
private boolean postSingleEventForEventType(Object event, EventBus.PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 同步取出該事件對應的Subscriptions(訂閱物件集合)。
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 遍歷Subscriptions, 將事件 event 和對應的 Subscription(訂閱物件)傳遞給
// postingState 並呼叫postToSubscription方法對事件進 行處理。
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted = false;
try {
postToSubscription(subscription, event, postingState.isMainThread);
aborted = postingState.canceled;
} finally {
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
if (aborted) {
break;
}
}
return true;
}
return false;
}
接下來檢視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(執行緒模式),之後根據threadMode來分別處理。如果threadMode是
MAIN,若提交事件的執行緒是主執行緒,則通過反射直接執行訂閱的方法;若其不是主執行緒,則需要
mainThreadPoster 將我們的訂閱事件新增到主執行緒佇列中。mainThreadPoster 是HandlerPoster型別的,繼承
自Handler,通過Handler將訂閱方法切換到主執行緒執行。
訂閱者取消註冊
取消註冊則需要呼叫unregister方法,如下所示:
public synchronized void unregister(Object subscriber) {
// 通過 subscriber找到subscribedTypes(事件型別集合)。
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
// 遍歷 subscribedTypes,並呼叫 unsubscribeByEventType方法
unsubscribeByEventType(subscriber, eventType);
}
// 將subscriber對應的eventType從 typesBySubscriber 中移除。
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
我們在訂閱者註冊的過程中講到過typesBySubscriber,它是一個map集合。接下來看unsubscribeByEventType方法:
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
// 重要標記...
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
註釋處通過eventType來得到對應的Subscriptions(訂閱物件集合),並在for迴圈中判斷如果 Subscription (訂閱物件)的subscriber(訂閱者)屬性等於傳進來的subscriber,則從Subscriptions中移除該Subscription。