EventBus源碼分析

EventBus

EventBus是一個為Android和Java平臺設計的發布/訂閱事件總線

image

EventBus有以下特點:

  • 簡化組件之間的通信
    • 將事件發送方和事件接收方解耦
    • 很好的使用于ActivitisFragments后臺線程
    • 避免復雜、易出錯的依賴
  • 簡化你的代碼
  • 體積小(~50K jar)
  • 有100,000,000+次相關APP安裝,證明EventBus的可靠性
  • 還有其他額外的功能

集成到項目

gradle配置:

implementation 'org.greenrobot:eventbus:3.1.1'

使用(只需3步)

  1. 定義事件

    public static class MessageEvent { /* 如果有需要,可以聲明相應的屬性 */ }

  2. 聲明訂閱方法

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {/* Do something */};

需要@Subscribe注解,默認的threadModeThreadMode.MAIN

注冊反注冊訂閱,比如在ActivitiesFragments中根據生命周期方法去注冊和反注冊

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

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }
  1. 發送事件

    EventBus.getDefault().post(new MessageEvent());

源碼解析

register

/**
 * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
 * are no longer interested in receiving events.
 * <p/>
 * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
 * The {@link Subscribe} annotation also allows configuration like {@link
 * ThreadMode} and priority.
 */
public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);// -> 1
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);// -> 2
        }
    }
}

注釋:
注冊subscriber用來接收事件,當不再希望接收到事件發送時必須要調用unregister取消注冊
subscriber必須包含帶Subscribe注解的方法,Subscribe注解可配置ThreadModepriority

  • 注釋1處代碼:

    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

根據sbuscriber的class去查找帶有@subscribe注解的方法,findSubscriberMethods方法:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);// -> 3
    if (subscriberMethods != null) {
        return subscriberMethods;
    }

    if (ignoreGeneratedIndex) {// -> 4
        subscriberMethods = findUsingReflection(subscriberClass);// -> 5
    } else {
        subscriberMethods = findUsingInfo(subscriberClass);// -> 6
    }
    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;
    }
}
  • 注釋3處代碼

先從緩存中去查找該subscriber中訂閱的方法,如果查到,直接返回。
METHOD_CACHE緩存中的數據是在register后添加的,但是unregister的時候并不會清掉,這樣當一個subscriber注冊完,然后反注冊,下次再注冊的時候,不需要再去查找其中訂閱的方法。

  • 注釋4處的代碼

如果上一步沒有查到相應的方法,就會走到這一步,先根據ignoreGeneratedIndex判斷是否忽略索引查找,如果忽略,則執行注釋5處的代碼,不管你是否添加了index所有,都利用反射去查找subscriber中訂閱的方法列表;如果不忽略,則執行6處的代碼,先從索引index中去查找,如果沒有索引或者索引中沒有找到,再考慮利用反射的方式去查找。
關于索引index的使用后面會提到。

  • 注釋5處的代碼

調用findUsingReflection方法:

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {// -> 7
        findUsingReflectionInSingleClass(findState);// -> 8
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}


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) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            if (parameterTypes.length == 1) {
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                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");
        }
    }
}
  • 注釋7處的代碼

這里之所以使用while循環而不用if判斷,是因為除了查找當前subscriber還需要查找其向上的繼承鏈,findState.moveToSuperclass();就是用來控制向上查找的,EventBus中所有的繼承鏈查找都是用這種方式,不要迷惑就好。

  • 注釋8處的代碼

這里就是調用了findUsingReflectionInSingleClass去用反射的方式查找subscriber中訂閱的方法列表,代碼很簡單,就是普通的反射使用,看不懂的問我吧。

反射的邏輯就這些

再回到注釋4處的代碼繼續分析另外一種查找方法列表的方式:

  • 注釋6處的代碼

調用findUsingInfo方法:

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        findState.subscriberInfo = getSubscriberInfo(findState);// -> 9
        if (findState.subscriberInfo != null) {
            SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
            for (SubscriberMethod subscriberMethod : array) {
                if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                    findState.subscriberMethods.add(subscriberMethod);
                }
            }
        } else {
            findUsingReflectionInSingleClass(findState);// -> 10
        }
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}
  • 注釋9處代碼

調用getSubscriberInfo方法:

private SubscriberInfo getSubscriberInfo(FindState findState) {
    if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
        SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
        if (findState.clazz == superclassInfo.getSubscriberClass()) {
            return superclassInfo;
        }
    }
    if (subscriberInfoIndexes != null) {
        for (SubscriberInfoIndex index : subscriberInfoIndexes) {
            SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
            if (info != null) {
                return info;
            }
        }
    }
    return null;
}

這里有兩個分支,第一次register的時候,第一個分支條件是不會成立的,我們看第二個分支:

這里的subscriberInfoIndexes就是我們通過EventBus的注解生成的index索引,然后調用EventBus.builder().addIndex(new MyEventBusIndex()).build();添加的,這個索引的作用就是把本來運行時通過反射查找訂閱方法的邏輯換成了編譯器自動生成文件,然后運行時在該文件中直接去查找的方式,從而提高了效率,index索引的方式后面會介紹。

  • 注釋10處的代碼

如果我們沒有添加index索引,那么代碼9處得到的findState.subscriberInfo就是null,代碼就會走到注釋10處,注釋10處的邏輯和上面注釋8處的邏輯一樣,都是通過反射去查找訂閱方法。

到這里,不管通過哪種方式,訂閱的方法列表已經找到了,我們回到注釋1處接著往下看:

  • 注釋2處的代碼:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //獲取事件類型
    Class<?> eventType = subscriberMethod.eventType;
    // 將訂閱者和訂閱者中的訂閱方法打包成一個Subscription對象
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions == null) {
        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();
    // 遍歷訂閱了該event類型的方法,根據priority把新訂閱的方法放到合適的位置
    for (int i = 0; i <= size; i++) {
        if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }

    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);
        }
    }
}

至此,register流程已經走完。

post事件流程

post事件的流程很簡單,就是通過反射調用相應的方法(訂閱的方法在上一步已經找到并存到了相應的集合中)即可。

public void post(Object event) {
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    if (!postingState.isPosting) {
        postingState.isMainThread = isMainThread();
        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);// -> 1
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}
  • 注釋1處代碼

調用postSingleEvent方法:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) { // -> 2
        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); // -> 3
        }
    } else {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass); // -> 4
    }
    if (!subscriptionFound) {
        if (logNoSubscriberMessages) {
            logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}
  • 注釋2處代碼

eventInheritance:該屬性可以在EventBus的Build中初始化,默認是true。

true的情況舉個例子:
A和B是兩個Event,并且A extends B
X和Y是兩個方法,X訂閱了事件A,Y訂閱了事件B
post A事件,同時會post B事件,那么X和Y都會收到事件

fasle的情況就是:post哪個事件,就只會發送這一個事件,不會發送它的父類事件,上面這個例子,如果eventInheritance為false,post A的時候Y就不會收到事件

  • 注釋3和注釋4代碼

都調用了postSingleEventForEventType方法:

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 {
                postToSubscription(subscription, event, postingState.isMainThread);// -> 5
                aborted = postingState.canceled;
            } finally {
                postingState.event = null;
                postingState.subscription = null;
                postingState.canceled = false;
            }
            if (aborted) {
                break;
            }
        }
        return true;
    }
    return false;
}
  • 注釋5處代碼:

這里就是遍歷到該event中的所有訂閱方法,挨個給他們發送事件,具體的發送邏輯就是代碼5處的postToSubscription方法:

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    switch (subscription.subscriberMethod.threadMode) {
        case POSTING://直接在當前線程發送
            invokeSubscriber(subscription, event);
            break;
        case MAIN:
            if (isMainThread) {//如果發送事件是在主線程,直接發送
                invokeSubscriber(subscription, event);
            } else {//如果發送事件不是在主線程,加入到主線程的事件隊列里面等待發送
                mainThreadPoster.enqueue(subscription, event);
            }
            break;
        case MAIN_ORDERED:// 沒太看懂和MAIN有啥區別
            if (mainThreadPoster != null) {
                mainThreadPoster.enqueue(subscription, event);
            } else {
                // temporary: technically not correct as poster not decoupled from subscriber
                invokeSubscriber(subscription, event);
            }
            break;
        case BACKGROUND:
            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);
    }
}

void invokeSubscriber(Subscription subscription, Object event) {
    try {
        subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
    } catch (InvocationTargetException e) {
        handleSubscriberException(subscription, event, e.getCause());
    } catch (IllegalAccessException e) {
        throw new IllegalStateException("Unexpected exception", e);
    }
}

這里就是根據不同的ThreadMode去執行不同的邏輯了,invokeSubscriber就是通過反射的方式去調用方法,沒什么可說的。

unregister

public synchronized void unregister(Object subscriber) {
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        typesBySubscriber.remove(subscriber);
    } else {
        logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

unregister的時候,會把該subscriber中的訂閱方法都從集合中移除掉,同時也會把該subscriber從相應的集合中移除掉。

索引index

EventBus提供一個注解處理器,可以在編譯期把你項目中所有regisger的class和所有的 @Subscribe 方法給整合起來,生成一個特殊的類,類似下面:

/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();// key就是register的對象, value就是該對象中@subscribe的方法集合

        putIndex(new SimpleSubscriberInfo(cn.jerry.webviewdemo.FirstActivity.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onEventArrived", cn.jerry.webviewdemo.CustomEvent.class),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    // 根據class對象獲取該對象中@Subscribe注解的方法列表
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}

代碼運行的時候,再遇到register邏輯,會直接從這個索引中查找相應的方法列表,從而避免了相應的反射操作,上面提到的register流程的注釋9處:

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

推薦閱讀更多精彩內容

  • EventBus源碼分析(一) EventBus官方介紹為一個為Android系統優化的事件訂閱總線,它不僅可以很...
    蕉下孤客閱讀 4,043評論 4 42
  • 簡介 前面我學習了如何使用EventBus,還有了解了EventBus的特性,那么接下來我們一起來學習EventB...
    eirunye閱讀 467評論 0 0
  • 前面對EventBus 的簡單實用寫了一篇,相信大家都會使用,如果使用的還不熟,或者不夠6,可以花2分鐘瞄一眼:h...
    gogoingmonkey閱讀 319評論 0 0
  • EventBus源碼分析 Android開發中我們最常用到的可以說就是EventBus了,今天我們來深入研究一下E...
    BlackFlag閱讀 512評論 3 4
  • EventBus源碼分析(二) 在之前的一篇文章EventBus源碼分析(一)分析了EventBus關于注冊注銷以...
    蕉下孤客閱讀 1,673評論 0 10