前面一篇文章講解了EventBus的使用块请,但是作為開發(fā)人員徙菠,不能只停留在僅僅會用的層面上笼恰,我們還需要弄清楚它的內部實現(xiàn)原理社证。所以本篇博文將分析EventBus的源碼篡诽,看看究竟它是如何實現(xiàn)“發(fā)布/訂閱”功能的。
相關文章
EventBus使用詳解
EventBus源碼解析
事件注冊
根據(jù)前一講EventBus使用詳解我們已經(jīng)知道EventBus使用首先是需要注冊的蝇裤,注冊事件的代碼如下:
EventBus.getDefault().register(this);
EventBus對外提供了一個register方法來進行事件注冊栓辜,該方法接收一個Object類型的參數(shù),下面看下register方法的源碼:
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
// 判斷該類是否是匿名內部類
boolean forceReflection = subscriberClass.isAnonymousClass();
List<SubscriberMethod> subscriberMethods =
subscriberMethodFinder.findSubscriberMethods(subscriberClass, forceReflection);
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
該方法首先獲取獲取傳進來參數(shù)的Class對象垛孔,然后判斷該類是否是匿名內部類藕甩。然后根據(jù)這兩個參數(shù)通過subscriberMethodFinder.findSubscriberMethods方法獲取所有的事件處理方法。
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, boolean forceReflection) {
String key = subscriberClass.getName();
List<SubscriberMethod> subscriberMethods;
synchronized (METHOD_CACHE) {
subscriberMethods = METHOD_CACHE.get(key);
}
if (subscriberMethods != null) {
//緩存命中周荐,直接返回
return subscriberMethods;
}
if (INDEX != null && !forceReflection) {
// 如果INDEX不為空狭莱,并且subscriberClass為非匿名內部類悯姊,
// 則通過findSubscriberMethodsWithIndex方法查找事件處理函數(shù)
subscriberMethods = findSubscriberMethodsWithIndex(subscriberClass);
if (subscriberMethods.isEmpty()) {
//如果結果為空,則使用findSubscriberMethodsWithReflection方法再查找一次
subscriberMethods = findSubscriberMethodsWithReflection(subscriberClass);
}
} else {
//INDEX為空或者subscriberClass未匿名內部類贩毕,使用findSubscriberMethodsWithReflection方法查找
subscriberMethods = findSubscriberMethodsWithReflection(subscriberClass);
}
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
//存入緩存并返回
synchronized (METHOD_CACHE) {
METHOD_CACHE.put(key, subscriberMethods);
}
return subscriberMethods;
}
}
通過名字我們就知道這個方法是獲取subscriberClass類中所有的事件處理方法(即使用了@Subscribe的方法)悯许。該方法首先會從緩存METHOD_CACHE中去獲取事件處理方法,如果緩存中不存在辉阶,則需要通過findSubscriberMethodsWithIndex或者findSubscriberMethodsWithReflection方法獲取所有事件處理方法先壕,獲取到之后先存入緩存再返回。
這個方法里面有個INDEX對象谆甜,我們看看它是個什么鬼:
/** Optional generated index without entries from subscribers super classes */
private static final SubscriberIndex INDEX;
static {
SubscriberIndex newIndex = null;
try {
Class<?> clazz = Class.forName("de.greenrobot.event.GeneratedSubscriberIndex");
newIndex = (SubscriberIndex) clazz.newInstance();
} catch (ClassNotFoundException e) {
Log.d(EventBus.TAG, "No subscriber index available, reverting to dynamic look-up");
// Fine
} catch (Exception e) {
Log.w(EventBus.TAG, "Could not init subscriber index, reverting to dynamic look-up", e);
}
INDEX = newIndex;
}
由上面代碼可以看出EventBus會試圖加載一個de.greenrobot.event.GeneratedSubscriberIndex類并創(chuàng)建對象賦值給INDEX垃僚,但是EventBus3.0 beta并沒有為我們提供該類(可能后續(xù)版本會提供)。所以INDEX為null规辱。
我們再返回findSubscriberMethods方法谆棺,我們知道INDEX已經(jīng)為null了,所以必然會調用findSubscriberMethodsWithReflection方法查找所有事件處理函數(shù):
private List<SubscriberMethod> findSubscriberMethodsWithReflection(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = new ArrayList<SubscriberMethod>();
Class<?> clazz = subscriberClass;
HashSet<String> eventTypesFound = new HashSet<String>();
StringBuilder methodKeyBuilder = new StringBuilder();
while (clazz != null) {
String name = clazz.getName();
// 如果查找的類是java罕袋、javax或者android包下面的類改淑,則過濾掉
if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
// Skip system classes, this just degrades performance
break;
}
// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
// 通過反射查找所有該類中所有方法
Method[] methods = clazz.getDeclaredMethods();
for (Method method : methods) {
int modifiers = method.getModifiers();
// 事件處理方法必須為public,這里過濾掉所有非public方法
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
// 事件處理方法必須只有一個參數(shù)
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
String methodName = method.getName();
Class<?> eventType = parameterTypes[0];
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(methodName);
methodKeyBuilder.append('>').append(eventType.getName());
String methodKey = methodKeyBuilder.toString();
if (eventTypesFound.add(methodKey)) {
// Only add if not already found in a sub class
// 只有在子類中沒有找到浴讯,才會添加到subscriberMethods
ThreadMode threadMode = subscribeAnnotation.threadMode();
subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification) {
// 如果某個方法加了@Subscribe注解朵夏,并且不是1個參數(shù),則拋出EventBusException異常
if (method.isAnnotationPresent(Subscribe.class)) {
String methodName = name + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
}
} else if (strictMethodVerification) {
// 如果某個方法加了@Subscribe注解榆纽,并且不是public修飾仰猖,則拋出EventBusException異常
if (method.isAnnotationPresent(Subscribe.class)) {
String methodName = name + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}
// 會繼續(xù)查找父類的方法
clazz = clazz.getSuperclass();
}
return subscriberMethods;
}
該方法主要作用就是找出subscriberClass類以及subscriberClass的父類中所有的事件處理方法(添加了@Subscribe注解,訪問修飾符為public并且只有一個參數(shù))奈籽。值得注意的是:如果子類與父類中同時存在了相同事件處理函數(shù)饥侵,則父類中的不會被添加到subscriberMethods。
好了衣屏,查找事件處理函數(shù)的過程已經(jīng)完了躏升,我們繼續(xù)回到register方法中:
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
找到事件處理函數(shù)后,會遍歷找到的所有事件處理函數(shù)并調用subscribe方法將所有事件處理函數(shù)注冊到EventBus中勾拉。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
// 獲取訂閱了某種類型數(shù)據(jù)的 Subscription 煮甥。 使用了 CopyOnWriteArrayList ,這個是線程安全的藕赞,
// CopyOnWriteArrayList 會在更新的時候琉挖,重新生成一份 copy赃额,其他線程使用的是
// copy,不存在什么線程安全性的問題。
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<Subscription>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//如果已經(jīng)被注冊過了侵蒙,則拋出EventBusException異常
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
// Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
// subscriberMethod.method.setAccessible(true);
// Got to synchronize to avoid shifted positions when adding/removing concurrently
// 根據(jù)優(yōu)先級將newSubscription查到合適位置
synchronized (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;
}
}
}
//將處理事件類型添加到typesBySubscriber
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<Class<?>>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
// 如果該事件處理方法為粘性事件,即設置了“sticky = true”,則需要調用checkPostStickyEventToSubscription
// 判斷是否有粘性事件需要處理,如果需要處理則觸發(fā)一次事件處理函數(shù)
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);
}
}
}
如果事件處理函數(shù)設置了“sticky = true”染坯,則會調用checkPostStickyEventToSubscription處理粘性事件。
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
if (stickyEvent != null) {
// If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
// --> Strange corner case, which we don't take care of here.
postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
}
}
如果存在粘性事件丘逸,則立即調用postToSubscription觸發(fā)該事件的事件處理函數(shù)单鹿。postToSubscription函數(shù)后面講post時會講到。
至此深纲,整個register過程就介紹完了仲锄。
總結一下,整個過程分為3步:
- 查找注冊的類中所有的事件處理函數(shù)(添加了@Subscribe注解且訪問修飾符為public的方法)
- 將所有事件處理函數(shù)注冊到EventBus
- 如果有事件處理函數(shù)設置了“sticky = true”湃鹊,則立即處理該事件
post事件
register過程講完后儒喊,我們知道了EventBus如何找到我們定義好的事件處理函數(shù)。有了這些事件處理函數(shù)币呵,當post相應事件的時候怀愧,EventBus就會觸發(fā)訂閱該事件的處理函數(shù)。具體post過程是怎樣的呢余赢?我們看看代碼:
public void post(Object event) {
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
if (!postingState.isPosting) {
// 標識post的線程是否是主線程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
postingState.isPosting = true;
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
// 循環(huán)處理eventQueue中的每一個event對象
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
// 處理完之后重置postingState的一些標識信息
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
currentPostingThreadState是一個ThreadLocal類型芯义,里面存儲了PostingThreadState;
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
/** For ThreadLocal, much faster to set (and get multiple values). */
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
PostingThreadState包含了一個事件隊列eventQueue和一些標志信息没佑。eventQueue存放所有待post的事件對象毕贼。
我們再回到post方法,首先會將event對象添加到事件隊列eventQueue中蛤奢。然后判斷是否有事件正在post,如果沒有則會遍歷eventQueue中每一個event對象陶贼,并且調用postSingleEvent方法post該事件啤贩。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
// 如果允許事件繼承,則會調用lookupAllEventTypes查找所有的父類和接口類
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的事件沒有被注冊拜秧,則post一個NoSubscriberEvent事件
post(new NoSubscriberEvent(this, event));
}
}
}
如果允許事件繼承痹屹,則會調用lookupAllEventTypes查找所有的父類和接口類。
private List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
synchronized (eventTypesCache) {
List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<Class<?>>();
Class<?> clazz = eventClass;
while (clazz != null) {
eventTypes.add(clazz);
addInterfaces(eventTypes, clazz.getInterfaces());
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
}
這個方法很簡單枉氮,就是查找eventClass類的所有父類和接口志衍,并將其保存到eventTypesCache中,方便下次使用聊替。
我們再回到postSingleEvent方法楼肪。不管允不允許事件繼承,都會執(zhí)行postSingleEventForEventType方法post事件惹悄。
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
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;
}
在postSingleEventForEventType方法中春叫,會已eventClass為key從subscriptionsByEventType對象中獲取Subscription列表。在上面講register的時候我們已經(jīng)看到EventBus在register的時候會將Subscription列表存儲在subscriptionsByEventType中。接下來會遍歷subscriptions列表然后調用postToSubscription方法進行下一步處理暂殖。
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
switch (subscription.subscriberMethod.threadMode) {
case PostThread:
// 如果該事件處理函數(shù)沒有指定線程模型或者線程模型為PostThread
// 則調用invokeSubscriber在post的線程中執(zhí)行事件處理函數(shù)
invokeSubscriber(subscription, event);
break;
case MainThread:
// 如果該事件處理函數(shù)指定的線程模型為MainThread
// 并且當前post的線程為主線程价匠,則調用invokeSubscriber在當前線程(主線程)中執(zhí)行事件處理函數(shù)
// 如果post的線程不是主線程,將使用mainThreadPoster.enqueue該事件處理函數(shù)添加到主線程的消息隊列中
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case BackgroundThread:
// 如果該事件處理函數(shù)指定的線程模型為BackgroundThread
// 并且當前post的線程為主線程呛每,則調用backgroundPoster.enqueue
// 如果post的線程不是主線程踩窖,則調用invokeSubscriber在當前線程(非主線程)中執(zhí)行事件處理函數(shù)
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);
}
}
該方法主要是根據(jù)register注冊的事件處理函數(shù)的線程模型在指定的線程中觸發(fā)事件處理函數(shù)。在上一講EventBus使用詳解中已經(jīng)講過EventBus的線程模型相關概念了晨横,不明白的可以回去看看洋腮。
mainThreadPoster、backgroundPoster和asyncPoster分別是HandlerPoster颓遏、BackgroundPoster和AsyncPoster的對象徐矩,其中HandlerPoster繼承自Handle,BackgroundPoster和AsyncPoster繼承自Runnable叁幢。
我們主要看看HandlerPoster滤灯。
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
在EventBus的構造函數(shù)中,我們看到mainThreadPoster初始化的時候曼玩,傳入的是Looper.getMainLooper()鳞骤。所以此Handle是運行在主線程中的。
mainThreadPoster.enqueue方法:
void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
enqueue方法最終會調用sendMessage方法黍判,所以該Handle的handleMessage方法會被調用豫尽。
@Override
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調用事件處理函數(shù)顷帖。
BackgroundPoster和AsyncPoster繼承自Runnable美旧,并且會在enqueue方法中調用eventBus.getExecutorService().execute(this);具體run方法大家可以自己去看源碼,最終都會調用eventBus.invokeSubscriber方法贬墩。我們看看eventBus.invokeSubscriber方法的源碼:
void invokeSubscriber(PendingPost pendingPost) {
Object event = pendingPost.event;
Subscription subscription = pendingPost.subscription;
PendingPost.releasePendingPost(pendingPost);
if (subscription.active) {
invokeSubscriber(subscription, event);
}
}
該方法會調用invokeSubscriber方法進一步處理:
void invokeSubscriber(Subscription subscription, Object event) {
try {
// 通過反射調用事件處理函數(shù)
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
該方法最終會通過反射來調用事件處理函數(shù)榴嗅。至此,整個post過程分析完了陶舞。
總結一下整個post過程嗽测,大致分為3步:
- 將事件對象添加到事件隊列eventQueue中等待處理
- 遍歷eventQueue隊列中的事件對象并調用postSingleEvent處理每個事件
- 找出訂閱過該事件的所有事件處理函數(shù),并在相應的線程中執(zhí)行該事件處理函數(shù)
取消事件注冊
上面已經(jīng)分析了EventBus的register和post過程肿孵,這兩個過程是EventBus的核心唠粥。不需要訂閱事件時需要取消事件注冊:
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unubscribeByEventType(subscriber, eventType);
}
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
取消事件注冊很簡單,只是將register過程注冊到EventBus的事件處理函數(shù)移除掉停做。
到這里晤愧,EventBus源碼我們已經(jīng)分析完了,如有不對的地方還望指點雅宾。