摘要:所以此是運(yùn)行在主線程中的。我們看看方法的源碼該方法會調(diào)用方法進(jìn)一步處理通過反射調(diào)用事件處理函數(shù)該方法最終會通過反射來調(diào)用事件處理函數(shù)。不需要訂閱事件時需要取消事件注冊取消事件注冊很簡單,只是將過程注冊到的事件處理函數(shù)移除掉。
事件注冊前面一篇文章講解了EventBus的使用,但是作為開發(fā)人員,不能只停留在僅僅會用的層面上,我們還需要弄清楚它的內(nèi)部實現(xiàn)原理。所以本篇博文將分析EventBus的源碼,看看究竟它是如何實現(xiàn)“發(fā)布/訂閱”功能的。
根據(jù)前一講EventBus使用詳解我們已經(jīng)知道EventBus使用首先是需要注冊的,注冊事件的代碼如下:
EventBus.getDefault().register(this);
EventBus對外提供了一個register方法來進(jìn)行事件注冊,該方法接收一個Object類型的參數(shù),下面看下register方法的源碼:
public void register(Object subscriber) { Class> subscriberClass = subscriber.getClass(); // 判斷該類是否是匿名內(nèi)部類 boolean forceReflection = subscriberClass.isAnonymousClass(); ListsubscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass, forceReflection); for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } }
該方法首先獲取獲取傳進(jìn)來參數(shù)的Class對象,然后判斷該類是否是匿名內(nèi)部類。然后根據(jù)這兩個參數(shù)通過subscriberMethodFinder.findSubscriberMethods方法獲取所有的事件處理方法。
ListfindSubscriberMethods(Class> subscriberClass, boolean forceReflection) { String key = subscriberClass.getName(); List subscriberMethods; synchronized (METHOD_CACHE) { subscriberMethods = METHOD_CACHE.get(key); } if (subscriberMethods != null) { //緩存命中,直接返回 return subscriberMethods; } if (INDEX != null && !forceReflection) { // 如果INDEX不為空,并且subscriberClass為非匿名內(nèi)部類, // 則通過findSubscriberMethodsWithIndex方法查找事件處理函數(shù) subscriberMethods = findSubscriberMethodsWithIndex(subscriberClass); if (subscriberMethods.isEmpty()) { //如果結(jié)果為空,則使用findSubscriberMethodsWithReflection方法再查找一次 subscriberMethods = findSubscriberMethodsWithReflection(subscriberClass); } } else { //INDEX為空或者subscriberClass未匿名內(nèi)部類,使用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了,所以必然會調(diào)用findSubscriberMethodsWithReflection方法查找所有事件處理函數(shù):
private ListfindSubscriberMethodsWithReflection(Class> subscriberClass) { List subscriberMethods = new ArrayList (); Class> clazz = subscriberClass; HashSet eventTypesFound = new HashSet (); 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ù)并調(diào)用subscribe方法將所有事件處理函數(shù)注冊到EventBus中。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class> eventType = subscriberMethod.eventType; // 獲取訂閱了某種類型數(shù)據(jù)的 Subscription 。 使用了 CopyOnWriteArrayList ,這個是線程安全的, // CopyOnWriteArrayList 會在更新的時候,重新生成一份 copy,其他線程使用的是 // copy,不存在什么線程安全性的問題。 CopyOnWriteArrayListsubscriptions = subscriptionsByEventType.get(eventType); Subscription newSubscription = new Subscription(subscriber, subscriberMethod); if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList (); 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 > subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList >(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); // 如果該事件處理方法為粘性事件,即設(shè)置了“sticky = true”,則需要調(diào)用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 ). Set , Object>> entries = stickyEvents.entrySet(); for (Map.Entry , 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ù)設(shè)置了“sticky = true”,則會調(diào)用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()); } }
如果存在粘性事件,則立即調(diào)用postToSubscription觸發(fā)該事件的事件處理函數(shù)。postToSubscription函數(shù)后面講post時會講到。
至此,整個register過程就介紹完了。
總結(jié)一下,整個過程分為3步:
查找注冊的類中所有的事件處理函數(shù)(添加了@Subscribe注解且訪問修飾符為public的方法)
將所有事件處理函數(shù)注冊到EventBus
如果有事件處理函數(shù)設(shè)置了“sticky = true”,則立即處理該事件
post事件register過程講完后,我們知道了EventBus如何找到我們定義好的事件處理函數(shù)。有了這些事件處理函數(shù),當(dāng)post相應(yīng)事件的時候,EventBus就會觸發(fā)訂閱該事件的處理函數(shù)。具體post過程是怎樣的呢?我們看看代碼:
public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List
currentPostingThreadState是一個ThreadLocal類型,里面存儲了PostingThreadState;
private final ThreadLocalcurrentPostingThreadState = new ThreadLocal () { @Override protected PostingThreadState initialValue() { return new PostingThreadState(); } }; /** For ThreadLocal, much faster to set (and get multiple values). */ final static class PostingThreadState { final List
PostingThreadState包含了一個事件隊列eventQueue和一些標(biāo)志信息。eventQueue存放所有待post的事件對象。
我們再回到post方法,首先會將event對象添加到事件隊列eventQueue中。然后判斷是否有事件正在post,如果沒有則會遍歷eventQueue中每一個event對象,并且調(diào)用postSingleEvent方法post該事件。
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { Class> eventClass = event.getClass(); boolean subscriptionFound = false; if (eventInheritance) { // 如果允許事件繼承,則會調(diào)用lookupAllEventTypes查找所有的父類和接口類 List> 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)); } } }
如果允許事件繼承,則會調(diào)用lookupAllEventTypes查找所有的父類和接口類。
private List> lookupAllEventTypes(Class> eventClass) { synchronized (eventTypesCache) { List > eventTypes = eventTypesCache.get(eventClass); if (eventTypes == null) { eventTypes = new ArrayList >(); 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) { CopyOnWriteArrayListsubscriptions; 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列表然后調(diào)用postToSubscription方法進(jìn)行下一步處理。
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case PostThread: // 如果該事件處理函數(shù)沒有指定線程模型或者線程模型為PostThread // 則調(diào)用invokeSubscriber在post的線程中執(zhí)行事件處理函數(shù) invokeSubscriber(subscription, event); break; case MainThread: // 如果該事件處理函數(shù)指定的線程模型為MainThread // 并且當(dāng)前post的線程為主線程,則調(diào)用invokeSubscriber在當(dāng)前線程(主線程)中執(zhí)行事件處理函數(shù) // 如果post的線程不是主線程,將使用mainThreadPoster.enqueue該事件處理函數(shù)添加到主線程的消息隊列中 if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case BackgroundThread: // 如果該事件處理函數(shù)指定的線程模型為BackgroundThread // 并且當(dāng)前post的線程為主線程,則調(diào)用backgroundPoster.enqueue // 如果post的線程不是主線程,則調(diào)用invokeSubscriber在當(dāng)前線程(非主線程)中執(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的線程模型相關(guān)概念了,不明白的可以回去看看。
mainThreadPoster、backgroundPoster和asyncPoster分別是HandlerPoster、BackgroundPoster和AsyncPoster的對象,其中HandlerPoster繼承自Handle,BackgroundPoster和AsyncPoster繼承自Runnable。
我們主要看看HandlerPoster。
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
在EventBus的構(gòu)造函數(shù)中,我們看到mainThreadPoster初始化的時候,傳入的是Looper.getMainLooper()。所以此Handle是運(yùn)行在主線程中的。
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方法最終會調(diào)用sendMessage方法,所以該Handle的handleMessage方法會被調(diào)用。
@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; } }
在該方法中,最終還是會調(diào)用eventBus.invokeSubscriber調(diào)用事件處理函數(shù)。
BackgroundPoster和AsyncPoster繼承自Runnable,并且會在enqueue方法中調(diào)用eventBus.getExecutorService().execute(this);具體run方法大家可以自己去看源碼,最終都會調(diào)用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); } }
該方法會調(diào)用invokeSubscriber方法進(jìn)一步處理:
void invokeSubscriber(Subscription subscription, Object event) { try { // 通過反射調(diào)用事件處理函數(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); } }
該方法最終會通過反射來調(diào)用事件處理函數(shù)。至此,整個post過程分析完了。
總結(jié)一下整個post過程,大致分為3步:
將事件對象添加到事件隊列eventQueue中等待處理
遍歷eventQueue隊列中的事件對象并調(diào)用postSingleEvent處理每個事件
找出訂閱過該事件的所有事件處理函數(shù),并在相應(yīng)的線程中執(zhí)行該事件處理函數(shù)
取消事件注冊上面已經(jīng)分析了EventBus的register和post過程,這兩個過程是EventBus的核心。不需要訂閱事件時需要取消事件注冊:
/** Unregisters the given subscriber from all event classes. */ public synchronized void unregister(Object subscriber) { List> 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)分析完了,如有不對的地方還望指點。
文章版權(quán)歸作者所有,未經(jīng)允許請勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。
轉(zhuǎn)載請注明本文地址:http://specialneedsforspecialkids.com/yun/70534.html
摘要:音樂團(tuán)隊分享數(shù)據(jù)綁定運(yùn)行機(jī)制分析一個項目搞定所有主流架構(gòu)單元測試一個項目搞定所有主流架構(gòu)系列的第二個項目。代碼開源,展示了的用法,以及如何使用進(jìn)行測試,還有用框架對的進(jìn)行單元測試。 Android 常用三方框架的學(xué)習(xí) Android 常用三方框架的學(xué)習(xí) likfe/eventbus3-intellij-plugin AS 最新可用 eventbus3 插件,歡迎品嘗 簡單的 MVP 模...
閱讀 3316·2021-11-25 09:43
閱讀 1304·2021-11-23 09:51
閱讀 3609·2021-10-11 11:06
閱讀 3698·2021-08-31 09:41
閱讀 3597·2019-08-30 15:53
閱讀 3510·2019-08-30 15:53
閱讀 965·2019-08-30 15:43
閱讀 3307·2019-08-29 14:02