What?EventBus的核心竟然只是這兩個Map?

簡單介紹一下EventBus

其實EventBus大家都很熟悉了,就不過多去說它了。通常我們叫它事件總線,其實它更像是廣播,觀察者模式,一方發送消息多方接收。在EventBus的創建訂閱過程中,最重要的就是有兩個關鍵的Map,這兩個鍵值對里面存儲了我們定義的訂閱方法和相關的類,那到底是具體是怎么操作的呢,來源碼一探究竟。

下面的代碼基于EventBus3.1.1

創建和訂閱消息

注冊

EventBus的注冊很簡單,

 @Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

這里一定要記住在onStop中注銷,避免在Activity關閉后還跟EventBus有聯系,然后造成內存泄漏。

接下來進入到方法中看一看:

單例模式

EventBus.getDefault

    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

這個方法很簡單,就是雙重校驗單例,繼續看register方法:

register方法

EventBus.register

    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();//注冊的類
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);//查找訂閱方法
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {//循環找到的所有方法
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

在register中,傳入的參數名為subscriber,意思就是訂閱者,類型為Object。在這個方法里有個List<SubscriberMethod>的列表,這個SubscriberMethod是什么呢?

public class SubscriberMethod {
    final Method method;//對應的方法
    final ThreadMode threadMode;//線程模式
    final Class<?> eventType;//消息類型
    final int priority;//優先級
    final boolean sticky;//是否支持粘性
    /** Used for efficient comparison */
    String methodString;//用于equal對比
}

其實這個類就保存了我們訂閱者里面定義的方法里面的所有信息。

線程模式

其中threadMode的定義如下:

  • ThreadMode.POSTING:默認的線程模式,在那個線程發送事件就在對應線程處理事件,避免了線程切換,效率高。

  • ThreadMode.MAIN:如在主線程(UI線程)發送事件,則直接在主線程處理事件;如果在子線程發送事件,則先將事件入隊列,然后通過 Handler 切換到主線程,依次處理事件。

  • ThreadMode.MAIN_ORDERED:無論在那個線程發送事件,都先將事件入隊列,然后通過 Handler 切換到主線程,依次處理事件。

  • ThreadMode.BACKGROUND:如果在主線程發送事件,則先將事件入隊列,然后通過線程池依次處理事件;如果在子線程發送事件,則直接在發送事件的線程處理事件。

  • ThreadMode.ASYNC:無論在那個線程發送事件,都將事件入隊列,然后通過線程池處理。

所以在register方法中的這個列表其實就是當前我們這個訂閱者類包含所有的接收方法。這里通過subscriberMethodFinder.findSubscriberMethods(subscriberClass)方法獲取:

查找訂閱事件的方法(接收消息的方法)

SubscriberMethodFinder findSubscriberMethods


    private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);//首先從緩存中獲取
        if (subscriberMethods != null) {
            return subscriberMethods;//緩存有的話直接返回
        }

        if (ignoreGeneratedIndex) {//是否忽略注解
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass
                    + " and its super classes have no public methods with the @Subscribe annotation");
        } else {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);//加入到緩存中
            return subscriberMethods;
        }
    }

這里我們注意到有一個ignoreGeneratedIndex參數,這個屬性的值是在構造方法中獲取的

subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
    /** Forces the use of reflection even if there's a generated index (default: false). */
    public EventBusBuilder ignoreGeneratedIndex(boolean ignoreGeneratedIndex) {
        this.ignoreGeneratedIndex = ignoreGeneratedIndex;
        return this;
    }

從官方的注釋可以看出,這里默認值是false,所以是調用findUsingInfo方法:


    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);//初始化查找輔助類
        while (findState.clazz != null) {//這里就是我們register的類
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {//初始狀態為空,所以執行else
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();//查找父類
        }
        return getMethodsAndRelease(findState);//釋放資源
    }

FindState是查找輔助類,里面存儲了關于查找到的訂閱方法信息和相關類的信息:

static class FindState {
        final List<SubscriberMethod> subscriberMethods = new ArrayList<>();//訂閱的方法
        final Map<Class, Object> anyMethodByEventType = new HashMap<>();//通過消息類型獲取方法
        final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();//通過方法獲取訂閱的類
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

        Class<?> subscriberClass;
        Class<?> clazz;
        boolean skipSuperClasses;
        SubscriberInfo subscriberInfo;
}

在這里會執行else里面的findUsingReflectionInSingleClass方法,通過反射來查找訂閱方法

SubscriberMethodFinder findUsingReflectionInSingleClass

    private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        //循環所有的方法
        for (Method method : methods) {
            int modifiers = method.getModifiers();//獲取修飾符
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {//public,非abstract、static
                Class<?>[] parameterTypes = method.getParameterTypes();//獲取參數類型
                if (parameterTypes.length == 1) {//只能有一個參數
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);//獲取Subscribe注解
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];//獲取參數類型,也就是我們自定義的消息的類型
                        if (findState.checkAdd(method, eventType)) {//是否添加過這個方法
                            ThreadMode threadMode = subscribeAnnotation.threadMode();//獲取線程模式
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));//添加到數組中
                        }
                    }
                } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                    String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                    throw new EventBusException("@Subscribe method " + methodName +
                            "must have exactly 1 parameter but has " + parameterTypes.length);
                }
            } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
                String methodName = method.getDeclaringClass().getName() + "." + method.getName();
                throw new EventBusException(methodName +
                        " is a illegal @Subscribe method: must be public, non-static, and non-abstract");
            }
        }
    }

整個的過程就是遍歷所有的方法,然后判斷有Subscribe注解的方法,然后將方法的信息加到數組當中。在查找完畢之后,接下來回到register方法

    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

循環訂閱

拿到我們剛才的所有訂閱方法的數組,然后在循環中執行subscribe方法,這個方法執行訂閱操作:

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;//獲取我們自定義的消息類型
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);//新建一個訂閱類,這個類包含了訂閱的類和方法兩個屬性
        //subscriptionsByEventType是以eventType為key,Subscription數組為value的map
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {//為空的話創建數組,并加入到map中
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {//已經訂閱過,拋出異常
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }
        
        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {//將優先級更高的訂閱方法加入到數組中
                subscriptions.add(i, newSubscription);
                break;
            }
        }
        //typesBySubscriber是以對象為key,訂閱的方法的數組為value的map
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
        //粘性事件相關
        if (subscriberMethod.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);
            }
        }
    }

其實EventBus的register方法的內部具體做的事情很簡單,總的來說就是兩步:

  1. 通過反射查找我們使用了Subscribe注解的訂閱方法
  2. 循環遍歷找到的方法,然后加到關鍵的兩個map中(subscriptionsByEventTypetypesBySubscriber

subscriptionsByEventType:以eventType為key,Subscription數組為value

typesBySubscriber:以對象為key,訂閱的方法的數組為value

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

推薦閱讀更多精彩內容

  • 先吐槽一下博客園的MarkDown編輯器,推出的時候還很高興博客園支持MarkDown了,試用了下發現支持不完善就...
    Ten_Minutes閱讀 572評論 0 2
  • EventBus是一個Android開源庫,其使用發布/訂閱模式,以提供代碼間的松耦合。EventBus使用中央通...
    壯少Bryant閱讀 665評論 0 4
  • 我每周會寫一篇源代碼分析的文章,以后也可能會有其他主題.如果你喜歡我寫的文章的話,歡迎關注我的新浪微博@達達達達s...
    SkyKai閱讀 24,967評論 23 184
  • EventBus 是一款在 Android 開發中使用的發布/訂閱事件總線框架,基于觀察者模式,將事件的接收者和發...
    SheHuan閱讀 65,702評論 13 186
  • 項目地址:EventBus,本文分析版本: 3.1.1 一、概述 EventBus 是一個 Android 事件發...
    Yi__Lin閱讀 1,046評論 1 10