Android事件總線 EventBus 2.4 源碼分析

EventBus簡介

本篇基于EventBus 2.4撰寫。

Android optimized event bus that simplifies communication between Activities, Fragments, Threads, Services, etc. Less code, better quality.

上面是從官方repo拉來的代碼,大致是說簡化的組件之間的交流通信,減少代碼,提高質(zhì)量。

其實和EventBus最早是在qzone的代碼里認識的,空間內(nèi)部有一個叫eventcenter的東西,曾經(jīng)有優(yōu)化過一些,當時看源碼實現(xiàn)的時候發(fā)現(xiàn)的原來是根據(jù)EventBus改的一個實現(xiàn)。大概就是把annotation的實現(xiàn)改成了接口實現(xiàn),另外去掉了根據(jù)Event類型來找訂閱者的模式,完全通過Event的TYPE類型常量來判斷,register的時候直接指定對哪種TYPE感興趣,輔助的判斷則有事件發(fā)送者引用。這種實現(xiàn)見仁見智吧,雖然直接通過接口肯定是能提高性能的。這里要吐槽的是實現(xiàn)修改的時候,直接把很多對外的接口名字改掉了,何必呢。

EventBus的好處是顯而易見的,完全解耦了請求鏈之間的關(guān)系,避免了請求者被長持有,又比廣播更輕量,比LocalBroadcast則更強大,接口也簡單實用。缺點的話,像是各種Event的定義是一個工作量。

源碼分析 - 注冊(register)

EventBus.java:

private synchronized void register(Object subscriber, boolean sticky, int priority) {
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass());
    for (SubscriberMethod subscriberMethod : subscriberMethods) {
        subscribe(subscriber, subscriberMethod, sticky, priority);
    }
}

register的時候,大致就是去subscriber里面首先找到那些onEvent方法(目前實現(xiàn)仍然是根據(jù)onEvent這個前綴),尋找的時候會去判斷后綴,分為post線程、主線程、background線程,以及異步線程,官方repo提到這里之后在3.0可能會換成annotation的實現(xiàn)。

sticky參數(shù)是粘性事件概念,postSticky和registerSticky相對應(yīng),stickyEvent會記錄該EventType對應(yīng)的最后一次postSticky的事件,這樣在registerSticky的時候,會立即檢查是否有之前post的事件,從而避免了某些事件去實現(xiàn)自己的緩存。應(yīng)用場景大概就是某些activity/fragment感興趣的事件發(fā)生在創(chuàng)建前,這樣則可以避免必須實現(xiàn)緩存(當然事實上應(yīng)用場景還是比較少的,因為大部分東西我們還是會在哪里記錄一下)

SubscriberMethod.java:

final class SubscriberMethod {
    final Method method;
    final ThreadMode threadMode;
    final Class<?> eventType;
    /** Used for efficient comparison */
    String methodString;
}

SubscriberMethod里面記錄了Method引用,線程模式(在findSubscriberMethods里拿到的),eventType,以及用來提高method.equals性能的methodString。

接著再看subscribe方法的實現(xiàn),在register最后,對找到的所有方法都去執(zhí)行了一遍subscribe
EventBus.java:

// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
    Class<?> eventType = subscriberMethod.eventType;

    // CopyOnWriteArrayList就是個ImmutableArrayList, add/set等方法會返回一個新的ArrayList
    // subscriptionsByEventType是一個hashmap,key是事件類型,value則是訂閱者數(shù)組
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);


    Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);

    // 該eventType在map里還不存在,新建一下對應(yīng)的subscription數(shù)組,放進去map
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<Subscription>();
        subscriptionsByEventType.put(eventType, subscriptions);
    } else {
        // 重復(fù)注冊的時候拋出異常,這里如果應(yīng)用如果覺得無傷大雅其實可以直接return
        if (subscriptions.contains(newSubscription)) {
            throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                    + eventType);
        }
    }

    // 根據(jù)優(yōu)先級去添加到對應(yīng)的位置,高優(yōu)先級在前面也就會先處理
    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;
        }
    }

    // typesBySubscriber是另一個map,顧名思義是以subscriber為key的一個map,被用在
    // 1) isRegistered(Object subscriber)方法加速判斷是否已注冊,用空間換時間
    // 2) unregister的時候直接可以拿到subscriber訂閱的所有eventType,然后去從map移除,避免需要遍歷所有eventType的map
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<Class<?>>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    // 粘性事件的話,就去立刻找一下是否有之前post過的事件,有則立即post給該subscriber
    if (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<Class>).
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, 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);
        }
    }
}

源碼分析 - 發(fā)送事件(post)

再來看一下對應(yīng)的post邏輯

EventBus.java:

/** Posts the given event to the event bus. */
public void post(Object event) {
    // 獲得當前post線程的狀態(tài),實現(xiàn)貼在下面了,currentPostingThreadState是ThreadLocal<PostingThreadState>變量,每個線程get和set的都是單獨的一份數(shù)據(jù)
    PostingThreadState postingState = currentPostingThreadState.get();
    // 往事件隊列里面添加該event
    List<Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    // 如果當前不在posting事件
    if (!postingState.isPosting) {
        // 設(shè)置是否在主線程
        postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
        // 設(shè)置當前正在post事件
        postingState.isPosting = true;
        // canceled狀態(tài),拋出異常
        if (postingState.canceled) {
            throw new EventBusException("Internal error. Abort state was not reset");
        }
        try {
            // 循環(huán)post從eventQueue里面拿出來的event
            while (!eventQueue.isEmpty()) {
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            // 置位回去
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

final static class PostingThreadState {
    final List<Object> eventQueue = new ArrayList<Object>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    // 可以通過cancelEventDelivery去取消事件傳遞
    boolean canceled;
}

// 單個事件的post處理
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    // 繼承鏈處理,比如Event本身的父類的subscriber也會收到,getDefault的時候默認為true。
    if (eventInheritance) {
        List<Class<?>> 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) {
            // 沒想到還有這種邏輯吧,沒找到訂閱者的,則會發(fā)送一個NoSubscriberEvent出去
            post(new NoSubscriberEvent(this, event));
        }
    }
}

// 對特定的event去post單個事件
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    // 找到該事件的所有訂閱
    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 {
                // 結(jié)果實際post還在這個方法內(nèi)實現(xiàn)
                postToSubscription(subscription, event, postingState.isMainThread);
                aborted = postingState.canceled;
            } finally {
                postingState.event = null;
                postingState.subscription = null;
                postingState.canceled = false;
            }
            // 如果cancel了,則不再繼續(xù)傳遞事件
            if (aborted) {
                break;
            }
        }
        return true;
    }
    return false;
}

// 具體的事件分發(fā)
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    // 這里就是EventBus的一個很強大的功能了,根據(jù)訂閱者的訂閱方法監(jiān)聽線程去處理
    // 如果post和監(jiān)聽方法在同一個線程則立即invoke對應(yīng)方法
    // 否則會去入隊列到對應(yīng)線程handler進行處理
    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);
    }
}

End

大致就講了一下register和post這一對比較常用的接口,其他還有一些實現(xiàn)像是EventBusBuilder,SubscriberException,cancelEventDelivery,AsyncExecutor就不在這里進行贅述,之后可能會對AsyncExecutor單獨開一篇講一下,另外也會對otto的實現(xiàn)做一下分析。

原文見:http://blog.zhaiyifan.cn/2015/08/20/EventBus%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90/

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,739評論 6 534
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 98,634評論 3 419
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,653評論 0 377
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,063評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,835評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 55,235評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,315評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 42,459評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 49,000評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 40,819評論 3 355
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,004評論 1 370
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,560評論 5 362
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 44,257評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,676評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,937評論 1 288
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,717評論 3 393
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,003評論 2 374

推薦閱讀更多精彩內(nèi)容