前面一篇文章講解了EventBus的使用,可是做爲開發人員,不能只停留在僅僅會用的層面上,咱們還須要弄清楚它的內部實現原理。因此本篇博文將分析EventBus的源碼,看看究竟它是如何實現「發佈/訂閱」功能的。 html
相關文章
EventBus使用詳解
EventBus源碼解析java
根據前一講EventBus使用詳解咱們已經知道EventBus使用首先是須要註冊的,註冊事件的代碼以下:android
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方法獲取全部事件處理方法,獲取到以後先存入緩存再返回。app
這個方法裏面有個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。async
咱們再返回findSubscriberMethods方法,咱們知道INDEX已經爲null了,因此必然會調用findSubscriberMethodsWithReflection方法查找全部事件處理函數:ide
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」,則當即處理該事件
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源碼咱們已經分析完了,若有不對的地方還望指點。