EventBus內(nèi)部實(shí)現(xiàn)研究

4610b912c8fcc3cef70d70409845d688d53f20f7.jpg

簡(jiǎn)介

EventBus這東西相信很多人都用過(guò),是一種用于Android的事件發(fā)布-訂閱框架,由GreenRobot開(kāi)發(fā)谁榜,官方地址是:EventBus。它簡(jiǎn)化了應(yīng)用程序內(nèi)各個(gè)組件之間進(jìn)行通信的復(fù)雜度凡纳,尤其是Fragment之間進(jìn)行通信的問(wèn)題窃植,可以避免由于使用廣播通信而帶來(lái)的諸多不便。
此處我們并不探究EventBus的使用方法荐糜,而是通過(guò)深入理解常用接口的內(nèi)部邏輯來(lái)探究EventBus的整體內(nèi)部構(gòu)造巷怜,所以不熟悉EventBus的同學(xué)可以自行百度了解葛超。

通過(guò)unregister方法了解訂閱者(Subscriber)的緩存方式

首先我們先看unregister方法,一般反注冊(cè)方法都是直接清除訂閱者延塑,所以通過(guò)unregister方法來(lái)查找到訂閱者(Subscriber)的保存方式往往是最容易绣张。

public class EventBus {
     ......
    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    private final Map<Class<?>, Object> stickyEvents;
    ....
    /** Unregisters the given subscriber from all event classes. */
    public synchronized void unregister(Object subscriber) {
        //typesBySubscriber用來(lái)保存(訂閱者和該訂閱者訂閱的事件類型)關(guān)系
        //key:Subscriber,value:EventType列表
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            //遍歷訂閱者對(duì)應(yīng)的事件類型列表,一個(gè)一個(gè)清除
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            //移除typesBySubscriber中訂閱者以及事件類型對(duì)應(yīng)關(guān)系
            typesBySubscriber.remove(subscriber);
        } else {
            Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }
    /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        //subscriptionsByEventType用來(lái)保存事件類型和Subscription列表對(duì)應(yīng)關(guān)系
        //key:事件類型关带,value:Subscription里面包含訂閱者subscriber以及訂閱方法SubscriberMethod 
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            //遍歷訂閱者并一一移除
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }
    ....
}
final class Subscription {
    final Object subscriber;
    final SubscriberMethod subscriberMethod;
    /**
     * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
     * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
     */
    volatile boolean active;
    ....
}

通過(guò)閱讀上面源碼侥涵,我們可以很容易的得到訂閱者和事件的緩存方式:

  1. subscriptionsByEventType保存了事件類型以及Subscription列表鍵值對(duì),事實(shí)上subscriptionsByEventType直接將事件類型、訂閱者Subscribery以及訂閱方法SubscriberMethod 聯(lián)系在一起宋雏;此處完全可以大膽推測(cè):發(fā)送事件是通過(guò)查找該事件類型對(duì)應(yīng)的Subscription列表芜飘,然后遍歷Subscription列表并一一觸發(fā)對(duì)應(yīng)的訂閱者Subscriber中SubscriberMethod 方法的調(diào)用,最終實(shí)現(xiàn)事件發(fā)送磨总。
  2. typesBySubscriber保存了訂閱者以及訂閱者所訂閱的事件類型列表鍵值對(duì)嗦明;typesBySubscriber主要是在反注冊(cè)時(shí)用來(lái)輔助清理subscriptionsByEventType中的訂閱者。


    image.png

register方法究竟做了什么

看完unregister方法蚪燕,我們可以大概的推測(cè)register(Object subscriber)里面主要做了什么:解析訂閱者subscriber里面的帶@Subscribe注解的方法娶牌,獲取監(jiān)聽(tīng)的事件類型,并將對(duì)應(yīng)關(guān)系保存到subscriptionsByEventType和typesBySubscriber中馆纳!

public class EventBus {

    /**
     * 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();
        //查找訂閱者subscriber內(nèi)部的帶@Subscribe注解的回調(diào)方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            //遍歷監(jiān)聽(tīng)者帶@Subscribe注解的回調(diào)方法裙戏,進(jìn)而獲取并保存訂閱者和事件類型對(duì)應(yīng)關(guān)系
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //將subscriberMethod中的事件類型和訂閱者對(duì)應(yīng)關(guān)系保存到subscriptionsByEventType中
        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);
            }
        }
        //根據(jù)subscriberMethod中所帶的priority進(jìn)行排序,以便后續(xù)發(fā)送事件時(shí)快速的按優(yōu)先權(quán)排序發(fā)送
        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;
            }
        }
      //將訂閱者subscriber和事件類型的對(duì)應(yīng)關(guān)系保存到typesBySubscriber中
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        if (subscriberMethod.sticky) {//subscriberMethod被設(shè)置為接收粘性事件
            if (eventInheritance) {//默認(rèn)為true厕诡,考慮父類繼承層級(jí)關(guān)系
                // 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>).
                //必須考慮eventType的所有子類的現(xiàn)有粘性事件累榜。
                //注意:對(duì)大量粘性事件迭代所有事件可能效率低下,因此應(yīng)更改數(shù)據(jù)結(jié)構(gòu)以允許更有效的查找
                //(例如灵嫌,存儲(chǔ)超類子類的附加映射:Class  - > List <Class>)壹罚。
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();
                    //判斷eventType是否為candidateEventType的父類
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

   private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        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());
        }
    }
}

上面代碼中,我們可以很明顯的看到register是如何保存訂閱者和事件類型對(duì)應(yīng)關(guān)系的寿羞,同時(shí)我們也知道了@Subscribe注解中priority 和sticky字段的作用猖凛。接下來(lái)我們繼續(xù)查看上面跳過(guò)的重要一步,探究SubscriberMethod是如何被找到的:

class SubscriberMethodFinder {

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //從緩存中獲取subscriber內(nèi)部的訂閱回調(diào)方法
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {//忽略索引绪穆,強(qiáng)制使用反射(默認(rèn)false)
            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;
        }
    }

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        //生成findState 對(duì)象并初始化
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //將subscriber中的SubscriberMethod信息封裝到findState中
            findUsingReflectionInSingleClass(findState);
            //切換到父類辨泳,進(jìn)入下個(gè)循環(huán)獲取父類的SubscriberMethod信息
            findState.moveToSuperclass();
        }
        //回收數(shù)據(jù)并返回SubscriberMethod列表
        return getMethodsAndRelease(findState);
    }

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
         //生成findState 對(duì)象并初始化
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //從findState 和subscriberInfoIndexes中獲取subscriberInfo 列表,
            //但目前發(fā)現(xiàn)源碼里面getSubscriberInfo(findState)返回的總是空的玖院,
            //索引的使用跟開(kāi)發(fā)者的使用配置有關(guān)
            findState.subscriberInfo = getSubscriberInfo(findState);
            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 {
                /將subscriber中的SubscriberMethod信息通過(guò)反射封裝到findState中
                findUsingReflectionInSingleClass(findState);
            }
            //切換到父類菠红,進(jìn)入下個(gè)循環(huán)獲取父類的SubscriberMethod信息
            findState.moveToSuperclass();
        }
        //回收數(shù)據(jù)并返回SubscriberMethod列表
        return getMethodsAndRelease(findState);
    }

    private SubscriberInfo getSubscriberInfo(FindState findState) {
        //剛初始化的findState中findState.subscriberInfo總是空的
        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
        //subscriberInfoIndexes是由EventBus中的靜態(tài)變量EventBusBuilder DEFAULT_BUILDER傳遞過(guò)來(lái)的,
      //EventBusBuilder 中的addIndex(SubscriberInfoIndex index)沒(méi)有任何地方調(diào)用难菌,
      //而且subscriberInfoIndexes也沒(méi)有使用add方法添加數(shù)據(jù)试溯,所以subscriberInfoIndexes一直都是空的
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        //這里一直都返回空,所謂的索引其實(shí)一直沒(méi)用
        return null;
    }

    private FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        return new 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();
            //必須是public方法郊酒,不能是static和abstract方法
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();
                //必須只能有一個(gè)參數(shù)
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    //必須添加@Subscribe注解
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            //獲取注解中的信息并封裝到findState中
                            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");
            }
        }
    }

    private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        findState.recycle();
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                if (FIND_STATE_POOL[i] == null) {
                    FIND_STATE_POOL[i] = findState;
                    break;
                }
            }
        }
        return subscriberMethods;
    }

    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;

        void initForSubscriber(Class<?> subscriberClass) {
            this.subscriberClass = clazz = subscriberClass;
            skipSuperClasses = false;
            subscriberInfo = null;
        }

        void recycle() {
            subscriberMethods.clear();
            anyMethodByEventType.clear();
            subscriberClassByMethodKey.clear();
            methodKeyBuilder.setLength(0);
            subscriberClass = null;
            clazz = null;
            skipSuperClasses = false;
            subscriberInfo = null;
        }

        boolean checkAdd(Method method, Class<?> eventType) {
            // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
            // Usually a subscriber doesn't have methods listening to the same event type.
            Object existing = anyMethodByEventType.put(eventType, method);
            if (existing == null) {
                return true;
            } else {
                if (existing instanceof Method) {
                    if (!checkAddWithMethodSignature((Method) existing, eventType)) {
                        // Paranoia check
                        throw new IllegalStateException();
                    }
                    // Put any non-Method object to "consume" the existing Method
                    anyMethodByEventType.put(eventType, this);
                }
                return checkAddWithMethodSignature(method, eventType);
            }
        }

        private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
            methodKeyBuilder.setLength(0);
            methodKeyBuilder.append(method.getName());
            methodKeyBuilder.append('>').append(eventType.getName());

            String methodKey = methodKeyBuilder.toString();
            Class<?> methodClass = method.getDeclaringClass();
            Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
            if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
                // Only add if not already found in a sub class
                return true;
            } else {
                // Revert the put, old class is further down the class hierarchy
                subscriberClassByMethodKey.put(methodKey, methodClassOld);
                return false;
            }
        }

        void moveToSuperclass() {
            if (skipSuperClasses) {
                clazz = null;
            } else {
                clazz = clazz.getSuperclass();
                String clazzName = clazz.getName();
                /** Skip system classes, this just degrades performance. */
                if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
                    clazz = null;
                }
            }
        }
    }

}

SubscriberMethod的查找是EventBus的核心業(yè)務(wù)邏輯之一遇绞,仔細(xì)閱讀源碼后發(fā)現(xiàn)其實(shí)并不是很復(fù)雜键袱,邏輯方法還是比較清晰的;唯一的問(wèn)題是作者引入了索引的概念摹闽,但源碼里面似乎并沒(méi)有完全實(shí)現(xiàn)蹄咖,索引邏輯沒(méi)有真正的觸發(fā)。索引流程必須得在開(kāi)發(fā)者完成相關(guān)配置后才能跑付鹿。


image.png

事件的發(fā)送

看完了注冊(cè)和反注冊(cè)邏輯澜汤,接下來(lái)就是事件的發(fā)送了。其實(shí)了解完注冊(cè)和反注冊(cè)倘屹,我們基本上已經(jīng)知道事件發(fā)送是怎么一回事了,無(wú)非就是拿著事件類型去subscriptionsByEventType中獲取該類型事件的訂閱者列表慢叨,然后遍歷列表觸發(fā)SubscriberMethod的調(diào)用纽匙,唯一值得期待的就只有注解中的線程模式的處理。廢話不多說(shuō)拍谐,繼續(xù)看源碼:

public class EventBus {
    /** Posts the given event to the event bus. */
    public void post(Object event) {
        //獲取當(dāng)前發(fā)送狀態(tài)
        PostingThreadState postingState = currentPostingThreadState.get();
        //事件添加到發(fā)送隊(duì)列
        List<Object> eventQueue = postingState.eventQueue;
        eventQueue.add(event);

        if (!postingState.isPosting) {//不在發(fā)送中
            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
            postingState.isPosting = true;//標(biāo)記正在發(fā)送
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {//循環(huán)發(fā)送事件
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {//默認(rèn)為true烛缔,考慮父類繼承層級(jí)關(guān)系
            //通過(guò)查看event繼承的父類層級(jí)關(guān)系來(lái)確認(rèn)有幾個(gè)事件類型
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            for (int h = 0; h < countTypes; h++) {
                Class<?> clazz = eventTypes.get(h);
                //根據(jù)事件類型發(fā)送事件
                subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
            }
        } else {
             //根據(jù)事件類型發(fā)送事件
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        if (!subscriptionFound) {//沒(méi)找到訂閱者
            if (logNoSubscriberMessages) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        //根據(jù)事件類型獲取Subscription列表
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            //遍歷Subscription列表
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    //事件發(fā)送給訂閱者
                    postToSubscription(subscription, event, postingState.isMainThread);
                    aborted = postingState.canceled;
                } finally {
                    postingState.event = null;
                    postingState.subscription = null;
                    postingState.canceled = false;
                }
                if (aborted) {
                    break;
                }
            }
            return true;
        }
        return false;
    }

    private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING://與事件發(fā)送源同一線程
                //訂閱者的SubscriberMethod回調(diào)
                invokeSubscriber(subscription, event);
                break;
            case MAIN://主線程
                if (isMainThread) {
                    //訂閱者的SubscriberMethod回調(diào)
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            case BACKGROUND://后臺(tái)線程
                if (isMainThread) {
                    backgroundPoster.enqueue(subscription, event);
                } else {
                    //訂閱者的SubscriberMethod回調(diào)
                    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);
        }
    }
}

看完上面的代碼,我們總結(jié)一下事件的發(fā)送流程:
1轩拨、將新的事件添加的發(fā)送隊(duì)列中践瓷,然后判斷是否正在發(fā)送事件:如果是則不做其他處理,發(fā)送隊(duì)列中事件會(huì)自動(dòng)發(fā)送亡蓉;如果不是則觸發(fā)事件發(fā)送邏輯并標(biāo)記為正在發(fā)送晕翠。進(jìn)入發(fā)送狀態(tài)后,發(fā)送隊(duì)列中的事件會(huì)被一一發(fā)送直到隊(duì)列為空砍濒。隊(duì)列事件發(fā)送完了淋肾,標(biāo)記為未發(fā)送狀態(tài)。
2爸邢、從隊(duì)列中拿出待發(fā)送事件樊卓,通過(guò)查看事件event繼承的父類層級(jí)關(guān)系來(lái)確認(rèn)有幾個(gè)事件類型,然后再根據(jù)事件類型的個(gè)數(shù)來(lái)確認(rèn)事件event發(fā)幾次杠河。
3碌尔、根據(jù)各個(gè)事件類型獲取訂閱者列表,然后一一觸發(fā)訂閱者的SubscriberMethod方法券敌,進(jìn)而觸發(fā)回調(diào)唾戚。SubscriberMethod的觸發(fā)涉及到線程的處理,不過(guò)這里面的線程處理都是最基礎(chǔ)的處理方式待诅,沒(méi)有什么特別值得深究的颈走。mainThreadPoster是繼承Handler;asyncPoster和backgroundPoster都是繼承Runnable咱士,然后都被提交到線程池executorService中運(yùn)行立由。


image.png
image.png
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末轧钓,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子锐膜,更是在濱河造成了極大的恐慌毕箍,老刑警劉巖,帶你破解...
    沈念sama閱讀 211,042評(píng)論 6 490
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件道盏,死亡現(xiàn)場(chǎng)離奇詭異而柑,居然都是意外死亡,警方通過(guò)查閱死者的電腦和手機(jī)荷逞,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 89,996評(píng)論 2 384
  • 文/潘曉璐 我一進(jìn)店門媒咳,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái),“玉大人种远,你說(shuō)我怎么就攤上這事涩澡。” “怎么了坠敷?”我有些...
    開(kāi)封第一講書(shū)人閱讀 156,674評(píng)論 0 345
  • 文/不壞的土叔 我叫張陵妙同,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我膝迎,道長(zhǎng)粥帚,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 56,340評(píng)論 1 283
  • 正文 為了忘掉前任限次,我火速辦了婚禮芒涡,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘卖漫。我一直安慰自己拖陆,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,404評(píng)論 5 384
  • 文/花漫 我一把揭開(kāi)白布懊亡。 她就那樣靜靜地躺著依啰,像睡著了一般。 火紅的嫁衣襯著肌膚如雪店枣。 梳的紋絲不亂的頭發(fā)上速警,一...
    開(kāi)封第一講書(shū)人閱讀 49,749評(píng)論 1 289
  • 那天,我揣著相機(jī)與錄音鸯两,去河邊找鬼闷旧。 笑死,一個(gè)胖子當(dāng)著我的面吹牛钧唐,可吹牛的內(nèi)容都是我干的忙灼。 我是一名探鬼主播,決...
    沈念sama閱讀 38,902評(píng)論 3 405
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼该园!你這毒婦竟也來(lái)了酸舍?” 一聲冷哼從身側(cè)響起,我...
    開(kāi)封第一講書(shū)人閱讀 37,662評(píng)論 0 266
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤里初,失蹤者是張志新(化名)和其女友劉穎啃勉,沒(méi)想到半個(gè)月后,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體双妨,經(jīng)...
    沈念sama閱讀 44,110評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡淮阐,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,451評(píng)論 2 325
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了刁品。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片泣特。...
    茶點(diǎn)故事閱讀 38,577評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖挑随,靈堂內(nèi)的尸體忽然破棺而出状您,到底是詐尸還是另有隱情,我是刑警寧澤镀裤,帶...
    沈念sama閱讀 34,258評(píng)論 4 328
  • 正文 年R本政府宣布竞阐,位于F島的核電站缴饭,受9級(jí)特大地震影響暑劝,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜颗搂,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,848評(píng)論 3 312
  • 文/蒙蒙 一担猛、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧丢氢,春花似錦傅联、人聲如沸。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 30,726評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)。三九已至貌嫡,卻和暖如春比驻,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背岛抄。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 31,952評(píng)論 1 264
  • 我被黑心中介騙來(lái)泰國(guó)打工别惦, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留拥诡,地道東北人亚享。 一個(gè)月前我還...
    沈念sama閱讀 46,271評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像纪蜒,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子扰付,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,452評(píng)論 2 348

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

  • EventBus源碼分析 Android開(kāi)發(fā)中我們最常用到的可以說(shuō)就是EventBus了堤撵,今天我們來(lái)深入研究一下E...
    BlackFlag閱讀 507評(píng)論 3 4
  • EventBus基本使用 EventBus基于觀察者模式的Android事件分發(fā)總線。 從這個(gè)圖可以看出悯周,Even...
    顧氏名清明閱讀 617評(píng)論 0 1
  • 項(xiàng)目到了一定階段會(huì)出現(xiàn)一種甜蜜的負(fù)擔(dān):業(yè)務(wù)的不斷發(fā)展與人員的流動(dòng)性越來(lái)越大粒督,代碼維護(hù)與測(cè)試回歸流程越來(lái)越繁瑣。這個(gè)...
    fdacc6a1e764閱讀 3,174評(píng)論 0 6
  • EventBus用法及解析 EventBus介紹: EventBus主要是用來(lái)組件之間進(jìn)行信息傳遞的禽翼,相對(duì)于接口回...
    111_222閱讀 544評(píng)論 0 1
  • 湖沼有芙蓉屠橄,孤枝玉宇沖。 樓亭慚暗影闰挡,高志到云峰锐墙。
    海上經(jīng)過(guò)閱讀 163評(píng)論 1 8