轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/40920453,本文出自:【張鴻洋的博客】java
上一篇帶你們初步瞭解了EventBus的使用方式,詳見:Android EventBus實戰 沒聽過你就out了,本篇博客將解析EventBus的源碼,相信可以讓你們深刻理解該框架的實現,也能解決不少在使用中的疑問:爲何能夠這麼作?爲何這麼作很差呢?android
通常使用EventBus的組件類,相似下面這種方式:微信
public class SampleComponent extends Fragment { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); EventBus.getDefault().register(this); } public void onEventMainThread(param) { } public void onEventPostThread(param) { } public void onEventBackgroundThread(param) { } public void onEventAsync(param) { } @Override public void onDestroy() { super.onDestroy(); EventBus.getDefault().unregister(this); } }
看完代碼你們或許會有一些疑問:併發
一、代碼中還有一些以onEvent開頭的方法,這些方法是幹嗎的呢?app
在回答這個問題以前,我有一個問題,你咋不問register(this)是幹嗎的呢?其實register(this)就是去當前類,遍歷全部的方法,找到onEvent開頭的而後進行存儲。如今知道onEvent開頭的方法是幹嗎的了吧。框架
二、那onEvent後面的那些MainThread應該是什麼標誌吧?async
嗯,是的,onEvent後面能夠寫四種,也就是上面出現的四個方法,決定了當前的方法最終在什麼線程運行,怎麼運行,能夠參考上一篇博客或者細細往下看。ide
既然register了,那麼確定得說怎麼調用是吧。oop
EventBus.getDefault().post(param);
如今有沒有以爲,撇開專業術語:其實EventBus就是在內部存儲了一堆onEvent開頭的方法,而後post的時候,根據post傳入的參數,去找到匹配的方法,反射調用之。源碼分析
那麼,我告訴你,它內部使用了Map進行存儲,鍵就是參數的Class類型。知道是這個類型,那麼你以爲根據post傳入的參數進行查找仍是個事麼?
下面咱們就去看看EventBus的register和post真面目。
EventBus.getDefault().register(this);
首先:
EventBus.getDefault()其實就是個單例,和咱們傳統的getInstance一個意思:
/** Convenience singleton for apps using a process-wide EventBus instance. */ public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }
而後register應該是一個普通的方法,咱們去看看:
register公佈給咱們使用的有4個:
public void register(Object subscriber) { register(subscriber, DEFAULT_METHOD_NAME, false, 0); } public void register(Object subscriber, int priority) { register(subscriber, DEFAULT_METHOD_NAME, false, priority); } public void registerSticky(Object subscriber) { register(subscriber, DEFAULT_METHOD_NAME, true, 0); } public void registerSticky(Object subscriber, int priority) { register(subscriber, DEFAULT_METHOD_NAME, true, priority); }
private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) { List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(), methodName); for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod, sticky, priority); } }
subscriber 是咱們掃描類的對象,也就是咱們代碼中常見的this;
methodName 這個是寫死的:「onEvent」,用於肯定掃描什麼開頭的方法,可見咱們的類中都是以這個開頭。
sticky 這個參數,解釋源碼的時候解釋,暫時不用管
priority 優先級,優先級越高,在調用的時候會越先調用。
下面開始看代碼:
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(), methodName);
那麼不用說,確定是去遍歷該類內部全部方法,而後根據methodName去匹配,匹配成功的封裝成SubscriberMethod,最後返回一個List。下面看代碼:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, String eventMethodName) { String key = subscriberClass.getName() + '.' + eventMethodName; List<SubscriberMethod> subscriberMethods; synchronized (methodCache) { subscriberMethods = methodCache.get(key); } if (subscriberMethods != null) { return subscriberMethods; } subscriberMethods = new ArrayList<SubscriberMethod>(); Class<?> clazz = subscriberClass; HashSet<String> eventTypesFound = new HashSet<String>(); StringBuilder methodKeyBuilder = new StringBuilder(); while (clazz != null) { String name = clazz.getName(); 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.getMethods(); for (Method method : methods) { String methodName = method.getName(); if (methodName.startsWith(eventMethodName)) { int modifiers = method.getModifiers(); if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 1) { String modifierString = methodName.substring(eventMethodName.length()); ThreadMode threadMode; if (modifierString.length() == 0) { threadMode = ThreadMode.PostThread; } else if (modifierString.equals("MainThread")) { threadMode = ThreadMode.MainThread; } else if (modifierString.equals("BackgroundThread")) { threadMode = ThreadMode.BackgroundThread; } else if (modifierString.equals("Async")) { threadMode = ThreadMode.Async; } else { if (skipMethodVerificationForClasses.containsKey(clazz)) { continue; } else { throw new EventBusException("Illegal onEvent method, check for typos: " + method); } } 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.add(new SubscriberMethod(method, threadMode, eventType)); } } } else if (!skipMethodVerificationForClasses.containsKey(clazz)) { Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "." + methodName); } } } clazz = clazz.getSuperclass(); } if (subscriberMethods.isEmpty()) { throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called " + eventMethodName); } else { synchronized (methodCache) { methodCache.put(key, subscriberMethods); } return subscriberMethods; } }呵,代碼還真長;不過咱們直接看核心部分:
22行:看到沒,clazz.getMethods();去獲得全部的方法:
23-62行:就開始遍歷每個方法了,去匹配封裝了。
25-29行:分別判斷了是否以onEvent開頭,是不是public且非static和abstract方法,是不是一個參數。若是都複合,才進入封裝的部分。
32-45行:也比較簡單,根據方法的後綴,來肯定threadMode,threadMode是個枚舉類型:就四種狀況。
最後在54行:將method, threadMode, eventType傳入構造了:new SubscriberMethod(method, threadMode, eventType)。添加到List,最終放回。
注意下63行:clazz = clazz.getSuperclass();能夠看到,會掃描全部的父類,不只僅是當前類。
繼續回到register:
for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod, sticky, priority); }
// Must be called in synchronized block private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) { subscribed = true; Class<?> eventType = subscriberMethod.eventType; CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority); if (subscriptions == null) { subscriptions = new CopyOnWriteArrayList<Subscription>(); subscriptionsByEventType.put(eventType, subscriptions); } else { for (Subscription subscription : subscriptions) { if (subscription.equals(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); int size = subscriptions.size(); for (int i = 0; i <= size; i++) { if (i == size || newSubscription.priority > subscriptions.get(i).priority) { subscriptions.add(i, newSubscription); break; } } List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<Class<?>>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); if (sticky) { Object stickyEvent; synchronized (stickyEvents) { stickyEvent = stickyEvents.get(eventType); } 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()); } } }咱們的subscriberMethod中保存了method, threadMode, eventType,上面已經說了;
4-17行:根據subscriberMethod.eventType,去subscriptionsByEventType去查找一個CopyOnWriteArrayList<Subscription> ,若是沒有則建立。
順便把咱們的傳入的參數封裝成了一個:Subscription(subscriber, subscriberMethod, priority);
這裏的subscriptionsByEventType是個Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> ; 這個Map其實就是EventBus存儲方法的地方,必定要記住!
22-28行:實際上,就是添加newSubscription;而且是按照優先級添加的。能夠看到,優先級越高,會插到在當前List的前面。
30-35行:根據subscriber存儲它全部的eventType ; 依然是map;key:subscriber ,value:List<eventType> ;知道就行,非核心代碼,主要用於isRegister的判斷。
37-47行:判斷sticky;若是爲true,從stickyEvents中根據eventType去查找有沒有stickyEvent,若是有則當即發佈去執行。stickyEvent其實就是咱們post時的參數。
postToSubscription這個方法,咱們在post的時候會介紹。
到此,咱們register就介紹完了。
你只要記得一件事:掃描了全部的方法,把匹配的方法最終保存在subscriptionsByEventType(Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> )中;
eventType是咱們方法參數的Class,Subscription中則保存着subscriber, subscriberMethod(method, threadMode, eventType), priority;包含了執行改方法所需的一切。
register完畢,知道了EventBus如何存儲咱們的方法了,下面看看post它又是如何調用咱們的方法的。
再看源碼以前,咱們猜想下:register時,把方法存在subscriptionsByEventType;那麼post確定會去subscriptionsByEventType去取方法,而後調用。
下面看源碼:
/** Posts the given event to the event bus. */ public void post(Object event) { PostingThreadState postingState = currentPostingThreadState.get(); List<Object> eventQueue = postingState.eventQueue; eventQueue.add(event); if (postingState.isPosting) { return; } else { postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper(); 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; } } }
currentPostingThreadState是一個ThreadLocal類型的,裏面存儲了PostingThreadState;PostingThreadState包含了一個eventQueue和一些標誌位。
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() { @Override protected PostingThreadState initialValue() { return new PostingThreadState(); } }
10行:判斷當前是不是UI線程。
16-18行:遍歷隊列中的全部的event,調用postSingleEvent(eventQueue.remove(0), postingState)方法。
這裏你們會不會有疑問,每次post都會去調用整個隊列麼,那麼不會形成方法屢次調用麼?
能夠看到第7-8行,有個判斷,就是防止該問題的,isPosting=true了,就不會往下走了。
下面看postSingleEvent
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { Class<? extends Object> eventClass = event.getClass(); List<Class<?>> eventTypes = findEventTypes(eventClass); boolean subscriptionFound = false; int countTypes = eventTypes.size(); for (int h = 0; h < countTypes; h++) { Class<?> clazz = eventTypes.get(h); CopyOnWriteArrayList<Subscription> subscriptions; synchronized (this) { subscriptions = subscriptionsByEventType.get(clazz); } 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; } } subscriptionFound = true; } } if (!subscriptionFound) { Log.d(TAG, "No subscribers registered for event " + eventClass); if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) { post(new NoSubscriberEvent(this, event)); } } }
2-3行:根據event的Class,去獲得一個List<Class<?>>;其實就是獲得event當前對象的Class,以及父類和接口的Class類型;主要用於匹配,好比你傳入Dog extends Dog,他會把Animal也裝到該List中。
6-31行:遍歷全部的Class,到subscriptionsByEventType去查找subscriptions;哈哈,熟不熟悉,還記得咱們register裏面把方法存哪了不?
是否是就是這個Map;
12-30行:遍歷每一個subscription,依次去調用postToSubscription(subscription, event, postingState.isMainThread);
這個方法就是去反射執行方法了,你們還記得在register,if(sticky)時,也會去執行這個方法。
下面看它如何反射執行:
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { switch (subscription.subscriberMethod.threadMode) { case PostThread: invokeSubscriber(subscription, event); break; case MainThread: if (isMainThread) { invokeSubscriber(subscription, event); } else { mainThreadPoster.enqueue(subscription, event); } break; case BackgroundThread: 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); } }前面已經說過subscription包含了全部執行須要的東西,大體有:subscriber, subscriberMethod(method, threadMode, eventType), priority;
那麼這個方法:第一步根據threadMode去判斷應該在哪一個線程去執行該方法;
case PostThread:
void invokeSubscriber(Subscription subscription, Object event) throws Error { subscription.subscriberMethod.method.invoke(subscription.subscriber, event); }
case MainThread:
首先去判斷當前若是是UI線程,則直接調用;不然: mainThreadPoster.enqueue(subscription, event);把當前的方法加入到隊列,而後直接經過handler去發送一個消息,在handler的handleMessage中,去執行咱們的方法。說白了就是經過Handler去發送消息,而後執行的。
case BackgroundThread:
若是當前非UI線程,則直接調用;若是是UI線程,則將任務加入到後臺的一個隊列,最終由Eventbus中的一個線程池去調用
executorService = Executors.newCachedThreadPool();。
case Async:將任務加入到後臺的一個隊列,最終由Eventbus中的一個線程池去調用;線程池與BackgroundThread用的是同一個。
這麼說BackgroundThread和Async有什麼區別呢?
BackgroundThread中的任務,一個接着一個去調用,中間使用了一個布爾型變量handlerActive進行的控制。
Async則會動態控制併發。
到此,咱們完整的源碼分析就結束了,總結一下:register會把當前類中匹配的方法,存入一個map,而post會根據實參去map查找進行反射調用。分析這麼久,一句話就說完了~~
其實不用發佈者,訂閱者,事件,總線這幾個詞或許更好理解,之後你們問了EventBus,能夠說,就是在一個單例內部維持着一個map對象存儲了一堆的方法;post無非就是根據參數去查找方法,進行反射調用。
介紹了register和post;你們獲取還能想到一個詞sticky,在register中,如何sticky爲true,會去stickyEvents去查找事件,而後當即去post;
那麼這個stickyEvents什麼時候進行保存事件呢?
其實evevntbus中,除了post發佈事件,還有一個方法也能夠:
public void postSticky(Object event) { synchronized (stickyEvents) { stickyEvents.put(event.getClass(), event); } // Should be posted after it is putted, in case the subscriber wants to remove immediately post(event); }
你們再去看看EventBus中全部的public方法,無非都是一些狀態判斷,獲取事件,移除事件的方法;沒什麼好介紹的,基本見名知意。
好了,到此咱們的源碼解析就結束了,但願你們不只可以瞭解這些優秀框架的內部機理,更可以體會到這些框架的不少細節之處,併發的處理,不少地方,爲何它這麼作等等。
我建了一個QQ羣,方便你們交流。羣號:55032675
----------------------------------------------------------------------------------------------------------
博主部分視頻已經上線,若是你不喜歡枯燥的文本,請猛戳(初錄,期待您的支持):