高速Android開發系列通訊篇之EventBus


概述及基本概念

**EventBus**是一個Android端優化的publish/subscribe消息總線,簡化了應用程序內各組件間、組件與後臺線程間的通訊。比方請求網絡,等網絡返回時經過Handler或Broadcast通知UI,兩個Fragment之間需要經過Listener通訊,這些需求都可以經過**EventBus**實現。android

做爲一個消息總線。有三個基本的元素:緩存

  • Event:事件
  • Subscriber:事件訂閱者。接收特定的事件
  • Publisher:事件公佈者,用於通知Subscriber有事件發生

Event

**Event**可以是隨意類型的對象。網絡

Subscriber

在EventBus中。使用約定來指定事件訂閱者以簡化使用。即所有事件訂閱都都是以onEvent開頭的函數,詳細來講。函數的名字是onEvent,onEventMainThread,onEventBackgroundThread,onEventAsync這四個,這個和ThreadMode有關,後面再說。async

Publisher

可以在隨意線程任何位置發送事件。直接調用EventBus的`post(Object)`方法,可以本身實例化EventBus對象,但通常使用默認的單例就行了:`EventBus.getDefault()`,依據post函數參數的類型。會本身主動調用訂閱對應類型事件的函數。ide

ThreadMode

前面說了,Subscriber函數的名字僅僅能是那4個。因爲每個事件訂閱函數都是和一個`ThreadMode`相關聯的,ThreadMode指定了會調用的函數。有下面四個ThreadMode:函數

  • PostThread:事件的處理在和事件的發送在一樣的進程。因此事件處理時間不該太長。否則影響事件的發送線程,而這個線程多是UI線程。

    相應的函數名是onEvent。oop

  • MainThread: 事件的處理會在UI線程中運行。事件處理時間不能太長。這個不用說的,長了會ANR的。相應的函數名是onEventMainThread。
  • BackgroundThread:事件的處理會在一個後臺線程中運行,相應的函數名是onEventBackgroundThread,儘管名字是BackgroundThread,事件處理是在後臺線程。但事件處理時間仍是不該該太長,因爲假設發送事件的線程是後臺線程,會直接運行事件,假設當前線程是UI線程,事件會被加到一個隊列中,由一個線程依次處理這些事件。假設某個事件處理時間太長,會堵塞後面的事件的派發或處理。

  • Async:事件處理會在單獨的線程中運行。主要用於在後臺線程中運行耗時操做。每個事件會開啓一個線程(有線程池)。但最好限制線程的數目。

依據事件訂閱都函數名稱的不一樣,會使用不一樣的ThreadMode。比假設在後臺線程載入了數據想在UI線程顯示。訂閱者僅僅需把函數命名爲onEventMainThread。post

簡單使用

主要的使用步驟就是例如如下4步,點擊此連接查看樣例及介紹。優化

  1. 定義事件類型:
    `public class MyEvent {}`
  2. 定義事件處理方法:
    `public void onEventMainThread`
  3. 註冊訂閱者:
    `EventBus.getDefault().register(this)`
  4. 發送事件:
    `EventBus.getDefault().post(new MyEvent())`

實現

**EventBus**用法很是easy,但用一個東西。假設不瞭解它的實現用起來內心老是沒底,萬一出問題咋辦都不知道,因此仍是研究一下它的實現,確定要Read the fucking Code。事實上主要是`EventBus`這一個類。在看看Code時需要了解幾個概念與成員,瞭解了這些後實現就很是好理解了。this

  • EventType:onEvent\*函數中的參數。表示事件的類型
  • Subscriber:訂閱源,即調用register註冊的對象。這個對象內包括onEvent\*函數
  • SubscribMethod:`Subscriber`內某一特定的onEvent\*方法,內部成員包括一個`Method`類型的method成員表示這個onEvent\*方法,一個`ThreadMode`成員threadMode表示事件的處理線程。一個`Class<?

    >`類型的eventType成員表示事件的類型`EventType`。

  • Subscription,表示一個訂閱對象。包括訂閱源`Subscriber`,訂閱源中的某一特定方法`SubscribMethod`,這個訂閱的優先級`priopity`


瞭解了以上幾個概念後就可以看`EventBus`中的幾個重要成員了

複製代碼
// EventType -> List<Subscription>。事件到訂閱對象之間的映射
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

// Subscriber -> List<EventType>。訂閱源到它訂閱的的所有事件類型的映射
private final Map<Object, List<Class<?>>> typesBySubscriber;

// stickEvent事件。後面會看到
private final Map<Class<?>, Object> stickyEvents;

// EventType -> List<?

extends EventType>。事件到它的父事件列表的映射。即緩存一個類的所有父類 private static final Map<Class<?>, List<Class<?

>>> eventTypesCache = new HashMap<Class<?

>, List<Class<?>>>();

複製代碼

註冊事件:Register

經過`EventBus.getDefault().register`方法可以向`EventBus`註冊來訂閱事件。`register`有很是多種重載形式。但大都被標記爲`Deprecated`了,因此仍是不用爲好,前面說了事件處理方法都是以*onEvent*開頭,事實上是可以經過register方法改動的。但對應的方法被廢棄了,仍是不要用了。就用默認的*onEvent*,除下廢棄的register方法。還有下面4個**public**的`register`方法

複製代碼
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);
}
複製代碼

可以看到,這4個方法都調用了同一個方法:

複製代碼
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個參數是優先級。這兩個後面再說。

在上面這種方法中,使用了一個叫`SubscriberMethodFinder`的類,經過其`findSubscriberMethods`方法找到了一個`SubscriberMethod`列表。前面知道了`SubscriberMethod`表示Subcriber內一個onEvent\*方法,可以看出來`SubscriberMethodFinder`類的做用是在Subscriber中找到所有以methodName(即默認的onEvent)開頭的方法,每個找到的方法被表示爲一個`SubscriberMethod`對象。

`SubscriberMethodFinder`就再也不分析了。但有兩點需要知道:

  1. 所有事件處理方法**必需是`public void`類型**的,並且僅僅有一個參數表示*EventType*。

  2. `findSubscriberMethods`不只僅查找*Subscriber*內的事件處理方法,**同一時候還會查到它的繼承體系中的所有基類中的事件處理方法**。

找到*Subscriber*中的所有事件處理方法後。會對每個找到的方法(表示爲`SubscriberMethod`對象)調用`subscribe`方法註冊。`subscribe`方法幹了三件事:

  1. 依據`SubscriberMethod`中的*EventType*類型將`Subscribtion`對象存放在`subscriptionsByEventType`中。

    創建*EventType*到*Subscription*的映射。每個事件可以有多個訂閱者。

  2. 依據`Subscriber`將`EventType`存放在`typesBySubscriber`中,創建*Subscriber*到*EventType*的映射。每個Subscriber可以訂閱多個事件。
  3. 假設是*Sticky*類型的訂閱者。直接向它發送上個保存的事件(假設有的話)。

經過*Subscriber*到*EventType*的映射,咱們就可以很是方便地使一個Subscriber取消接收事件,經過*EventType*到*Sucscribtion*的映射。可以方便地將對應的事件發送到它的每一個訂閱者。

Post事件

直接調用`EventBus.getDefault().post(Event)就可以發送事件,依據Event的類型就可以發送到對應事件的訂閱者。

複製代碼
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`的定義:

複製代碼
final static class PostingThreadState {
    List<Object> eventQueue = new ArrayList<Object>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}
複製代碼

主要是有個成員`eventQueue`,由於是ThreadLocal,因此結果就是。每個線程有一個`PostingThreadState`對象,這個對象內部有一個事件的隊列,並且有一個成員`isPosting`表示現在是否正在派發事件,當發送事件開始時,會依次取出隊列中的事件發送出去,假設正在派發事件,那麼post直接把事件增長隊列後返回,還有個成員`isMainThread`。這個成員在實際派發事件時會用到。在`postSingleEvent`中會用到。

複製代碼
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中返回.

接下來進入第二步,遍歷第一步中獲得的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`了:

  • 假設是PostThread,直接運行
  • 假設是MainThread。推斷當前線程,假設原本就是UI線程就直接運行,不然增長`mainThreadPoster`隊列
  • 假設是後臺線程,假設當前是UI線程,增長`backgroundPoster`隊列。不然直接運行
  • 假設是Async。增長`asyncPoster`隊列

BackgroundPoster

複製代碼
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);
        }
    }
}
複製代碼

代碼比較簡單,事實上就是,待發送的事件被封裝成了`PendingPost`對象,`PendingPostQueue`是一個`PendingPost`對象的隊列,當`enqueue`時就把這個事件放到隊列中。`BackgroundPoster`事實上就是一個Runnable對象,當`enqueue`時,假設這個Runnable對象當前沒被運行。就將`BackgroundPoster`增長EventBus中的一個線程池中。當`BackgroundPoster`被運行時,會依次取出隊列中的事件進行派發。

當長時間無事件時`BackgroundPoster`所屬的線程被會銷燬。下次再Post事件時再建立新的線程。

HandlerPoster

`mainThreadPoster`是一個`HandlerPoster`對象。`HandlerPoster`繼承自`Handler`。構造函數中接收一個`Looper`對象,當向`HandlerPoster` enqueue事件時。會像`BackgroundPoster`同樣把這個事件增長隊列中。 僅僅是假設當前沒在派發消息就向自身發送Message

複製代碼
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");
            }
        }
    }
}
複製代碼

在`handleMessage`中會依次取出隊列中的消息交由`EventBus`直接調用事件處理函數。而`handleMessage`運行所在的線程就是構造函數中傳進來的`Looper`所屬的線程,在`EventBus`中構造`mainThreadPoster`時傳進來的是MainLooper,因此會在UI線程中運行。

AsyncPoster

`AsyncPoster`就簡單了,把每個事件都增長線程池中處理

public void enqueue(Subscription subscription, Object event) {
    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    queue.enqueue(pendingPost);
    EventBus.executorService.execute(this);
}

Stick Event

經過`registerSticky`可以註冊Stick事件處理函數,前面咱們知道了。不論是`register`仍是`registerSticky`最後都會調用`Subscribe`函數。在`Subscribe`中有這麼一段代碼:

 

也就是會依據事件類型從`stickyEvents`中查找是否有相應的事件。假設有,直接發送這個事件到這個訂閱者。而這個事件是何時存起來的呢。同`register`與`registerSticky`同樣。和`post`一塊兒的另外一個`postSticky`函數:

複製代碼
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());
    }
}
複製代碼

當經過`postSticky`發送一個事件時,這個類型的事件的最後一次事件會被緩存起來,當有訂閱者經過`registerSticky`註冊時,會把以前緩存起來的這個事件直接發送給它。

事件優先級Priority

`register`的函數重載中有一個可以指定訂閱者的優先級,咱們知道`EventBus`中有一個事件類型到List<Subscription>的映射,在這個映射中。所有的Subscription是按priority排序的,這樣當post事件時,優先級高的會先獲得機會處理事件。

優先級的一個應用就事,高優先級的事件處理函數可以最終事件的傳遞。經過`cancelEventDelivery`方法,但有一點需要注意,`這個事件的ThreadMode必須是PostThread`,並且僅僅能最終它在處理的事件。

# 缺點
沒法進程間通訊,假設一個應用內有多個進程的話就沒辦法了

# 注意事項及要點

  • 同一個onEvent函數不能被註冊兩次。因此不能在一個類中註冊同一時候還在父類中註冊
  • 當Post一個事件時。這個事件類的父類的事件也會被Post。
  • Post的事件無Subscriber處理時會Post `NoSubscriberEvent`事件,當調用Subscriber失敗時會Post `SubscriberExceptionEvent`事件。

其它

`EventBus`中還有個Util包。主要做用是可以經過`AsyncExecutor`運行一個Runnable,經過內部的RunnableEx(可以搜索異常的Runnable)當Runnable拋出異常時經過`EventBus`發消息顯示錯誤對話框。

沒太大興趣,不做分析

項目主頁: http://download.csdn.net/detail/androidstarjack/8925145

 一個很是easy的Demo,Activity中包括列表和詳情兩個Fragment,Activity啓動時載入一個列表,點擊列表後更新詳情數據:EventBusDemo

相關文章
相關標籤/搜索