轉載請標明出處: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開頭的方法是幹嗎的了吧。async
二、那onEvent後面的那些MainThread應該是什麼標誌吧?ide
嗯,是的,onEvent後面可以寫四種,也就是上面出現的四個方法。決定了當前的方法終於在什麼線程運行,怎麼運行。可以參考上一篇博客或者細細往下看。oop
既然register了,那麼確定得說怎麼調用是吧。post
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<?咱們的subscriberMethod中保存了method, threadMode, eventType。上面已經說了。>> 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()); } } }
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
----------------------------------------------------------------------------------------------------------
博主部分視頻已經上線。假設你不喜歡枯燥的文本。請猛戳(初錄。期待您的支持):