EventBus源碼解析
根據前一講EventBus使用詳解我們已經知道EventBus使用首先是需要注冊的,注冊事件的代碼如下:
EventBus.getDefault().register(this);
EventBus對外提供了一個register方法來進行事件注冊,該方法接收一個Object類型的參數,下面看下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); } }
該方法首先獲取獲取傳進來參數的Class對象,然后判斷該類是否是匿名內部類。然后根據這兩個參數通過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方法查找事件處理函數 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類并創建對象賦值給INDEX,但是EventBus3.0 beta并沒有為我們提供該類(可能后續版本會提供)。所以INDEX為null。
我們再返回findSubscriberMethods方法,我們知道INDEX已經為null了,所以必然會調用findSubscriberMethodsWithReflection方法查找所有事件處理函數:
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(); // 事件處理方法必須只有一個參數 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個參數,則拋出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"); } } } // 會繼續查找父類的方法 clazz = clazz.getSuperclass(); } return subscriberMethods; }
該方法主要作用就是找出subscriberClass類以及subscriberClass的父類中所有的事件處理方法(添加了@Subscribe注解,訪問修飾符為public并且只有一個參數)。值得注意的是:如果子類與父類中同時存在了相同事件處理函數,則父類中的不會被添加到subscriberMethods。
好了,查找事件處理函數的過程已經完了,我們繼續回到register方法中:
for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); }
找到事件處理函數后,會遍歷找到的所有事件處理函數并調用subscribe方法將所有事件處理函數注冊到EventBus中。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class<?> eventType = subscriberMethod.eventType; // 獲取訂閱了某種類型數據的 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 { //如果已經被注冊過了,則拋出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 // 根據優先級將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 // 判斷是否有粘性事件需要處理,如果需要處理則觸發一次事件處理函數 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); } } }
如果事件處理函數設置了“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觸發該事件的事件處理函數。postToSubscription函數后面講post時會講到。
至此,整個register過程就介紹完了。總結一下,整個過程分為3步:
- 查找注冊的類中所有的事件處理函數(添加了@Subscribe注解且訪問修飾符為public的方法)
- 將所有事件處理函數注冊到EventBus
- 如果有事件處理函數設置了“sticky = true”,則立即處理該事件
post事件
register過程講完后,我們知道了EventBus如何找到我們定義好的事件處理函數。有了這些事件處理函數,當post相應事件的時候,EventBus就會觸發訂閱該事件的處理函數。具體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 { // 循環處理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方法。不管允不允許事件繼承,都會執行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的時候我們已經看到EventBus在register的時候會將Subscription列表存儲在subscriptionsByEventType中。接下來會遍歷subscriptions列表然后調用postToSubscription方法進行下一步處理。
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case PostThread: // 如果該事件處理函數沒有指定線程模型或者線程模型為PostThread // 則調用invokeSubscriber在post的線程中執行事件處理函數 invokeSubscriber(subscription, event); break; case MainThread: // 如果該事件處理函數指定的線程模型為MainThread // 并且當前post的線程為主線程,則調用invokeSubscriber在當前線程(主線程)中執行事件處理函數 // 如果post的線程不是主線程,將使用mainThreadPoster.enqueue該事件處理函數添加到主線程的消息隊列中 if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case BackgroundThread: // 如果該事件處理函數指定的線程模型為BackgroundThread // 并且當前post的線程為主線程,則調用backgroundPoster.enqueue // 如果post的線程不是主線程,則調用invokeSubscriber在當前線程(非主線程)中執行事件處理函數 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); } }
該方法主要是根據register注冊的事件處理函數的線程模型在指定的線程中觸發事件處理函數。在上一講EventBus使用詳解中已經講過EventBus的線程模型相關概念了,不明白的可以回去看看。
mainThreadPoster、backgroundPoster和asyncPoster分別是HandlerPoster、BackgroundPoster和AsyncPoster的對象,其中HandlerPoster繼承自Handle,BackgroundPoster和AsyncPoster繼承自Runnable。
我們主要看看HandlerPoster。
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
在EventBus的構造函數中,我們看到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調用事件處理函數。
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 { // 通過反射調用事件處理函數 subscription.subscriberMethod.method.invoke(subscription.subscriber, event); } catch (InvocationTargetException e) { handleSubscriberException(subscription, event, e.getCause()); } catch (IllegalAccessException e) { throw new IllegalStateException("Unexpected exception", e); } }
該方法最終會通過反射來調用事件處理函數。至此,整個post過程分析完了。總結一下整個post過程,大致分為3步:
- 將事件對象添加到事件隊列eventQueue中等待處理
- 遍歷eventQueue隊列中的事件對象并調用postSingleEvent處理每個事件
- 找出訂閱過該事件的所有事件處理函數,并在相應的線程中執行該事件處理函數
取消事件注冊
上面已經分析了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的事件處理函數移除掉。
到這里,EventBus源碼我們已經分析完了,如有不對的地方還望指點。