當Android項目愈來愈龐大的時候,應用的各個部件之間的通訊變得愈來愈複雜,例如:當某一條件發生時,應用中有幾個部件對這個消息感興趣,那麼咱們一般採用的就是觀察者模式,使用觀察者模式有一個弊病就是部件之間的耦合度過高,在這裏將會詳細介紹Android中的解耦組件EventBus的使用。html
//定義事件類型: publicclassMyEvent{} //定義事件處理方法: publicvoid onEventMainThread //註冊訂閱者: EventBus.getDefault().register(this) //發送事件: EventBus.getDefault().post(newMyEvent()) //實現
// EventType -> List<Subscription>,事件到訂閱對象之間的映射 privatefinalMap<Class<?>,CopyOnWriteArrayList<Subscription>> subscriptionsByEventType; // Subscriber -> List<EventType>,訂閱源到它訂閱的的全部事件類型的映射 privatefinalMap<Object,List<Class<?>>> typesBySubscriber; // stickEvent事件,後面會看到 privatefinalMap<Class<?>,Object> stickyEvents; // EventType -> List<? extends EventType>,事件到它的父事件列表的映射。即緩存一個類的全部父類 privatestaticfinalMap<Class<?>,List<Class<?>>> eventTypesCache =newHashMap<Class<?>,List<Class<?>>>();
public void register(Object subscriber) { register(subscriber, defaultMethodName, false, 0); } public void register(Object subscriber, int priority) { register(subscriber, defaultMethodName, false, priority); } public void registerSticky(Object subscriber) { register(subscriber, defaultMethodName, true, 0); } public void registerSticky(Object subscriber, int priority) { register(subscriber, defaultMethodName, 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); } }
第一個參數就是訂閱源,第二個參數就是用到指定方法名約定的,默認爲*onEvent*開頭,說默認是實際上是能夠經過參數修改的,但前面說了,方法已被廢棄,最好不要用。第三個參數表示是不是*Sticky Event*,第4個參數是優先級,這兩個後面再說。java
在上面這個方法中,使用了一個叫`SubscriberMethodFinder`的類,經過其`findSubscriberMethods`方法找到了一個`SubscriberMethod`列表,前面知道了`SubscriberMethod`表示Subcriber內一個onEvent\*方法,能夠看出來`SubscriberMethodFinder`類的做用是在Subscriber中找到全部以methodName(即默認的onEvent)開頭的方法,每一個找到的方法被表示爲一個`SubscriberMethod`對象。android
`SubscriberMethodFinder`就再也不分析了,但有兩點須要知道: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; } } }
能夠看到post內使用了`PostingThreadState`的對象,而且是`ThreadLocal`,來看`PostingThreadState`的定義:git
final static class PostingThreadState { List<Object> eventQueue = new ArrayList<Object>(); boolean isPosting; boolean isMainThread; Subscription subscription; Object event; boolean canceled; }
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { Class<? extends Object> eventClass = event.getClass(); List<Class<?>> eventTypes = findEventTypes(eventClass); // 1 boolean subscriptionFound = false; int countTypes = eventTypes.size(); for (int h = 0; h < countTypes; h++) { // 2 Class<?> clazz = eventTypes.get(h); CopyOnWriteArrayList<Subscription> subscriptions; synchronized (this) { subscriptions = subscriptionsByEventType.get(clazz); } if (subscriptions != null && !subscriptions.isEmpty()) { // 3 for (Subscription subscription : subscriptions) { postingState.event = event; postingState.subscription = subscription; boolean aborted = false; try { postToSubscription(subscription, event, postingState.isMainThread); // 4 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)); } } }
來看一下`postSingleEvent`這個函數,首先看第一點,調用了`findEventTypes`這個函數,代碼不帖了,這個函數的應用就是,把這個類的類對象、實現的接口及父類的類對象存到一個List中返回.github
接下來進入第二步,遍歷第一步中獲得的List,對List中的每一個類對象(即事件類型)執行第三步操做,即找到這個事件類型的全部訂閱者向其發送事件。設計模式
能夠看到,當咱們Post一個事件時,這個事件的父事件(事件類的父類的事件)也會被Post,因此若是有個事件訂閱者接收Object類型的事件,那麼它就能夠接收到全部的事件。緩存
還能夠看到,實際是經過第四步中的`postToSubscription`來發送事件的,在發送前把事件及訂閱者存入了`postingState`中。再來看`postToSubscription`網絡
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); } }
這裏就用到`ThreadMode`了:異步
private final PendingPostQueue queue; public void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); synchronized (this) { queue.enqueue(pendingPost); if (!executorRunning) { executorRunning = true; EventBus.executorService.execute(this); } } }
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"); } } } }
public void enqueue(Subscription subscription, Object event) { PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); queue.enqueue(pendingPost); EventBus.executorService.execute(this); }
經過`registerSticky`能夠註冊Stick事件處理函數,前面咱們知道了,不管是`register`仍是`registerSticky`最後都會調用`Subscribe`函數,在`Subscribe`中有這麼一段代碼:async
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()); } }
也就是會根據事件類型從`stickyEvents`中查找是否有對應的事件,若是有,直接發送這個事件到這個訂閱者。
而這個事件是何時存起來的呢,同`register`與`registerSticky`同樣,和`post`一塊兒的還有一個`postSticky`函數
當經過`postSticky`發送一個事件時,這個類型的事件的最後一次事件會被緩存起來,當有訂閱者經過`registerSticky`註冊時,會把以前緩存起來的這個事件直接發送給它 。`register`的函數重載中有一個能夠指定訂閱者的優先級,咱們知道`EventBus`中有一個事件類型到List<Subscription>的映射,在這個映射中,全部的Subscription是按priority排序的,這樣當post事件時,優先級高的會先獲得機會處理事件。
優先級的一個應用就是,高優先級的事件處理函數能夠終止事件的傳遞,經過`cancelEventDelivery`方法,但有一點須要注意,`這個事件的ThreadMode必須是PostThread`,而且只能終止它在處理的事件。
沒法進程間通訊,若是一個應用內有多個進程的話就沒辦法了
//註冊和發佈事件的函數分別爲
registerSticky(…)和 postSticky(Object event)