上半部分主要是EventBus3.0架構分析,接下來開始EventBus3.0的源碼分析了。java
咱們從EventBus3.0使用方式開始源碼分析,先來分析註冊事件~git
註冊事件方式:github
EventBus.getDefault().register(this);
EventBus的getDefault()是一個單例,確保只有一個EventBus對象實例緩存
public static EventBus getDefault() { EventBus instance = defaultInstance; if (instance == null) { synchronized (EventBus.class) { instance = EventBus.defaultInstance; if (instance == null) { instance = EventBus.defaultInstance = new EventBus(); } } } return instance; }
EventBus構造方法作什麼呢?架構
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder(); public EventBus() { this(DEFAULT_BUILDER); }
在EventBus無參構造方法調用了有一個參數的構造方法,參數傳入的是EventBusBuilder對象,該對象配置EventBus相關默認的屬性。異步
EventBus(EventBusBuilder builder) { logger = builder.getLogger(); subscriptionsByEventType = new HashMap<>(); typesBySubscriber = new HashMap<>(); stickyEvents = new ConcurrentHashMap<>(); mainThreadSupport = builder.getMainThreadSupport(); mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null; 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來更改async
EventBus.builder() .logNoSubscriberMessages(false) .sendNoSubscriberEvent(false) .installDefaultEventBus();
接下來分析EventBus註冊重要的一個方法register,先看下它的源碼ide
public void register(Object subscriber) { // 獲取當前註冊類的Class對象 Class<?> subscriberClass = subscriber.getClass(); // 查找當前註冊類中被@Subscribe註解標記的全部方法 List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { // 遍歷全部的訂閱方法,完成註冊 for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }
從register方法源碼能夠看出,主要完成訂閱方法查找和註冊,訂閱方法查找由findSubscriberMethods完成,註冊由subscribe完成。
首先看下findSubscriberMethods方法源碼實現源碼分析
// 緩存訂閱方法,key:當前註冊類的Class value:訂閱方法集合 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; } // ignoreGeneratedIndex默認值爲false // 主要做用:是否忽略由APT(註解處理器)生成的訂閱索引 if (ignoreGeneratedIndex) { // 若是忽略,則使用反射技術查找全部被@Subscribe註解標記的全部訂閱方法 subscriberMethods = findUsingReflection(subscriberClass); } else { // 默認不忽略,可是若是沒有使用APT(註解處理器)生成的訂閱索引,則仍是經過反射技術查找 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; } }
findSubscriberMethods方法主要乾的事情很清晰,首先從緩存中獲取當前註冊類的訂閱方法,若是找到,直接返回;若是沒有找到,經過APT(註解處理器)或者反射技術查找當前註冊類中的全部訂閱方法,若是沒有找到,拋出異常,不然緩存到內存中,並返回當前註冊類中全部的訂閱方法。post
其中查找當前註冊類中的全部訂閱方法經過findUsingInfo方法實現
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) { // FindState FindState findState = prepareFindState(); findState.initForSubscriber(subscriberClass); while (findState.clazz != null) { // 若是沒有使用APT(註解處理器)生成訂閱方法索引,返回null,則進入else語句中 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); } // 從父類中繼續查找,直到父類爲null findState.moveToSuperclass(); } // 返回註冊類中全部的訂閱方法,並釋放findState中狀態,同時把findState對象放回緩存池中 return getMethodsAndRelease(findState); }
findUsingInfo方法主要是從當前註冊類及父類中查找全部的訂閱方法,首先從經過APT(註解處理器)生成訂閱方法索引中查找,若是沒有使用APT(註解處理器)生成,則經過反射技術查找。
先來看下經過反射技術怎麼去查找?關鍵方法findUsingReflectionInSingleClass源碼以下:
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的,且不能是ABSTRACT或者STATIC if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { Class<?>[] parameterTypes = method.getParameterTypes(); // 方法的參數必須是有一個 if (parameterTypes.length == 1) { Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); // 方法必須被@Subscribe註解標記 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"); } } }
訂閱方法的查找已經分析完了,而後就是subscribe方法源碼分析了
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { // 訂閱事件類型,也就是訂閱方法的參數類型 Class<?> eventType = subscriberMethod.eventType; // Subscription封裝當前註冊類的對象和訂閱方法 Subscription newSubscription = new Subscription(subscriber, subscriberMethod); // subscriptionsByEventType是一個Map,key爲訂閱事件類型,value爲Subscription集合 CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); 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); } } // 將newSubscription添加到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也是一個Map,key爲註冊類的對象,value爲當前註冊類中全部訂閱方法中的參數類型集合 List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); // 默認sticky爲false,表明不是粘性事件,下面代碼先不看,後面說到粘性事件再來分析它 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); } } }
subscribe方法中的subscriptionsByEventType和typesBySubscriber兩個Map。在事件發佈時用到
subscriptionsByEventType來完成事件的處理,在取消註冊時用到subscriptionsByEventType和typesBySubscriber這兩個Map,後面會具體分析到~~
取消註冊方式:
EventBus.getDefault().unregister(this);
取消註冊調用EventBus的unregister方法,下面是它的源碼
public synchronized void unregister(Object subscriber) { // typesBySubscriber是一個Map,註冊的時候已經將key爲當前註冊類的對象,value爲當前註冊類全部訂閱方法的參數類型放入當前Map中 List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber); // 若是subscribedTypes不爲null, 說明當前類有註冊 if (subscribedTypes != null) { for (Class<?> eventType : subscribedTypes) { // 根據事件類型eventType,取消訂閱 unsubscribeByEventType(subscriber, eventType); } // 將註冊的對象從Map中移除 typesBySubscriber.remove(subscriber); } else { logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass()); } }
從unregister方法源碼可知,先根據當前取消註冊類的對象從typesBySubscriber緩存中找到全部訂閱方法的事件類型,而後根據事件類型,取消訂閱。接下來看下unsubscribeByEventType源碼:
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) { // subscriptionsByEventType也是一個Map,註冊的時候已經將key爲訂閱事件類型,value爲Subscription對象集合放入當前Map中 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; // 移除Subscription subscriptions.remove(i); i--; size--; } } } }
從取消註冊源碼分析可知,主要是從typesBySubscriber和subscriptionsByEventType這兩個Map中移除註冊類對象和移除訂閱方法。
普通事件的發佈,能夠經過下面方式:
EventBus.getDefault().post("hello, eventbus!");
能夠看到發佈事件經過post方法完成
public void post(Object event) { // currentPostingThreadState是一個PostingThreadState類型的ThreadLocal // PostingThreadState維護者事件隊列和線程模型 PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; // 將要發送的事件先加入事件隊列中 eventQueue.add(event); // isPosting默認值爲false if (!postingState.isPosting) { // 是不是主線程 postingState.isMainThread = isMainThread(); 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; } } }
post方法先將要事件加入到事件隊列中,而後循環事件隊列,交給postSingleEvent方法處理
private void postSingleEvent(Object event, 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); } // 若是沒有註冊,subscriptionFound爲false if (!subscriptionFound) { if (logNoSubscriberMessages) { // logNoSubscriberMessages默認值爲true logger.log(Level.FINE, "No subscribers registered for event " + eventClass); } if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) { post(new NoSubscriberEvent(this, event)); } } }
postSingleEvent方法會查找該事件和它的繼承事件,而後交給postSingleEventForEventType方法處理
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) { CopyOnWriteArrayList<Subscription> subscriptions; synchronized (this) { // subscriptionsByEventType在註冊時,會將事件和訂閱方法加入 subscriptions = subscriptionsByEventType.get(eventClass); } // 若是沒有註冊,subscriptions就會爲null 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中會從註冊表subscriptionsByEventType中找出該事件的全部訂閱方法,交給postToSubscription方法處理
最後是事件的處理了,會根據ThreadMode線程模式切換線程處理事件
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 { // 若是發佈事件在子線程,先將事件入隊列,而後經過Handler切換到主線程執行 mainThreadPoster.enqueue(subscription, event); } break; // 要求在主線程處理事件 case MAIN_ORDERED: // 不管發佈事件在哪一個線程,都會把事件入隊列,而後經過Handler切換到主線程執行 if (mainThreadPoster != null) { mainThreadPoster.enqueue(subscription, event); } else { // temporary: technically not correct as poster not decoupled from subscriber invokeSubscriber(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); } }
線程切換其實就是根據訂閱事件方法的線程模型及發佈事件的線程來決定如何處理,處理方式分爲兩種:一種在相應的線程直接經過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); } }
還有一種就是先將事件入隊列(底層是雙向鏈表結構實現),而後交給Handler或者線程池處理。以ASYNC線程模型爲例, asyncPoster是AsyncPoster類的一個實例
class AsyncPoster implements Runnable, Poster { private final PendingPostQueue queue; private final EventBus eventBus; AsyncPoster(EventBus eventBus) { this.eventBus = eventBus; // PendingPostQueue是一個雙向鏈表 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); } }
先分析到這,接下來分析粘性事件,訂閱索引,AsyncExecutor等~~~