擼EventBus源碼

源碼是eventbus-3.1.1

代碼入口:

  • EventBus.getDefault().register(Object subscriber)注冊(cè)訂閱者
  • EventBus.getDefault().unregister(Object subscriber)注銷訂閱者
  • EventBus.getDefault().post(Object event)發(fā)送事件
  • @Subscribe()訂閱者

創(chuàng)建EventBus

EventBus.getDefault().register(Object subscriber)可以看到EventBus的使用是單例模式:

static volatile EventBus defaultInstance;

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

DCL的單例模式為什么靜態(tài)變量instance要使用volatile標(biāo)簽?

查看new EventBus()

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

public EventBus() {
    this(DEFAULT_BUILDER);
}

EventBus(EventBusBuilder builder) {
    logger = builder.getLogger();
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadSupport = builder.getMainThreadSupport();
    mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
    backgroundPoster = new BackgroundPoster(this);
    asyncPoster = new AsyncPoster(this);
    indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
    subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
            builder.strictMethodVerification, builder.ignoreGeneratedIndex);
    logSubscriberExceptions = builder.logSubscriberExceptions;
    logNoSubscriberMessages = builder.logNoSubscriberMessages;
    sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
    sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
    throwSubscriberException = builder.throwSubscriberException;
    eventInheritance = builder.eventInheritance;
    executorService = builder.executorService;
}

這里在new EventBus的時(shí)候又使用了構(gòu)造者模式。
EventBus中幾個(gè)主要的成員變量:

  • Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType
    這個(gè)subscriptionsByEventType的key是事件類,value是訂閱者list,其中l(wèi)ist使用的線程安全的CopyOnWriteArrayList。
  • Map<Object, List<Class<?>>> typesBySubscriber
    這個(gè)typesBySubscriber的key為訂閱者,value為訂閱者的事件list
  • Map<Class<?>, Object> stickyEvents
    這個(gè)stickyEvents為粘性事件,key為事件的類,value為事件對(duì)象

注冊(cè)

public void register(Object subscriber) {
    //獲取訂閱者類名
    Class<?> subscriberClass = subscriber.getClass();
    // 1   獲取訂閱者訂閱的方法   
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
    // 2  在同步塊中將訂閱方法進(jìn)行注冊(cè)
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

一般情況下register的入?yún)⑹茿ctivity、Service、Fragment這個(gè)有生命周期的對(duì)象,所有在對(duì)象的生命周期開始的地方進(jìn)行注冊(cè),并在生命周期結(jié)束的時(shí)候進(jìn)行注銷。

看標(biāo)注1處,這里使用subscriberMethodFinder的findSubscriberMethods()方法獲取訂閱者的訂閱方法:

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

可以看到方法中先查看緩存中是否存在此訂閱者的訂閱方法,如果沒有就通過findUsingInfo()進(jìn)行查找,然后將查找到的結(jié)果放入緩存,并返回結(jié)果。

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        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 {
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

這里通過findUsingReflectionInSingleClass(findState);方法進(jìn)行查找訂閱方法,查找完成后會(huì)繼續(xù)查找訂閱者類的父類的訂閱方法,直到當(dāng)前查找的類是系統(tǒng)類時(shí)跳出循環(huán)。

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

從名字就可以看出是通過反射的方法進(jìn)行查找,在查找的過程中通過遍歷每個(gè)訂閱者類的每個(gè)方法的注解,如有存在@Subscribe()則表明是訂閱方法,并將這個(gè)method的注解參數(shù)進(jìn)行解析,最終一并加入list中。

至此,注冊(cè)的第一步完成:獲取訂閱者類的訂閱方法(因?yàn)榉椒赡芏鄠€(gè),所有用list)。再看注冊(cè)的第二部分:

        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }

主要看subscribe(subscriber, subscriberMethod)方法。

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //獲取這個(gè)訂閱方法中訂閱的事件(訂閱方法的入?yún)ⅲ?        Class<?> eventType = subscriberMethod.eventType;
        //通過訂閱類和訂閱方法注冊(cè)一個(gè)訂閱對(duì)象Subscription
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        /**
         * 獲取訂閱當(dāng)前事件的所有訂閱對(duì)象,
         * 如果為空那就創(chuàng)建一個(gè)list用于存儲(chǔ),并將這個(gè)list放入subscriptionsByEventType中
         **/
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } 
        // 按優(yōu)先級(jí)順序插入當(dāng)前的訂閱對(duì)象
        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;
            }
        }
        //將當(dāng)前訂閱類作為key,訂閱事件作為value傳入typesBySubscriber中
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        //POST粘性事件
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
            //  包含事件父類的情況(默認(rèn)true)
                // 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);
            }
        }
    }

至此,訂閱的注冊(cè)完成,在完成注冊(cè)的時(shí)候會(huì)將訂閱的類、訂閱的方法、訂閱的事件統(tǒng)一存到EventBus對(duì)象中,為后面事件的發(fā)送進(jìn)行處理;粘性事件會(huì)在訂閱的類注冊(cè)完成的時(shí)候觸發(fā)訂閱方法。


注銷

    public synchronized void unregister(Object subscriber) {
        // 1 根據(jù)訂閱類獲取訂閱事件
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                // 2 解除訂閱事件和訂閱類的綁定關(guān)系
                unsubscribeByEventType(subscriber, eventType);
            }
            // 3 移除訂閱類
            typesBySubscriber.remove(subscriber);
        } 
        ...
    }

注銷方法中第一個(gè)注釋的地方是通過訂閱類獲取訂閱事件,然后對(duì)每一個(gè)訂閱事件解除與訂閱類的關(guān)系,最后移除訂閱類。

解除訂閱事件和訂閱類的綁定關(guān)系使用的是unsubscribeByEventType(subscriber, eventType);方法:

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        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--;
                }
            }
        }
    }

從subscriptionsByEventType中獲取所有訂閱事件對(duì)應(yīng)的訂閱者(Subscription),遍歷訂閱者list,找出所有訂閱類的Subscription,并從中移除。

注意代碼中l(wèi)ist的選擇刪除,每刪除一個(gè)元素,都有i--;size--;不然就會(huì)報(bào)索引越界的異常。


發(fā)送訂閱事件 post(Object event)


    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

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

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

        if (!postingState.isPosting) {
            // 2
            postingState.isMainThread = isMainThread();
            postingState.isPosting = true;
            if (postingState.canceled) {
                throw new EventBusException("Internal error. Abort state was not reset");
            }
            try {
                while (!eventQueue.isEmpty()) {
                    // 3
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

訂閱事件發(fā)送主要分三步:

  1. 從currentPostingThreadState中獲取當(dāng)前線程的信息:
  • 當(dāng)前線程的待發(fā)送事件對(duì)列
  • 發(fā)送狀態(tài)
    currentPostingThreadState是一個(gè)threadLocal對(duì)象,為每一個(gè)線程存儲(chǔ)訂閱事件的信息。
  1. 判斷當(dāng)前線程是不是主線程,后面可以看到主線程和子線程發(fā)送事件的方式不同
  2. 從頭開始逐一將當(dāng)前線程的訂閱事件發(fā)送出去,使用postSingleEvent(eventQueue.remove(0), postingState);方法。
    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
            // 1
            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 {
            // 2
            subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
        }
        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));
            }
        }
    }

注釋1處是對(duì)于訂閱事件的超類和接口一并進(jìn)行發(fā)送,注釋2處只發(fā)送訂閱事件,所以主要關(guān)注postSingleEventForEventType(event, postingState, eventClass)方法。

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 1
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    // 2
                    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;
    }

注釋1處獲取當(dāng)前訂閱事件對(duì)應(yīng)的所有訂閱對(duì)象;在注釋2處逐條進(jìn)行發(fā)送,使用postToSubscription(subscription, event, postingState.isMainThread);方法:

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

可以看出,這里針對(duì)訂閱方法的注解的不同,發(fā)送到不同的線程:

  • POSTING:通過發(fā)射直接調(diào)用訂閱方法,沒有線程切換,性能損耗最小
  • MAIN:如果發(fā)送事件的線程就是主線程,那就反射調(diào)用訂閱方法;如果不是,那就將訂閱事件加入主線程的發(fā)送隊(duì)列
  • MAIN_ORDER:對(duì)于Android,不論在哪個(gè)線程發(fā)送,都將訂閱事件加入主線程的發(fā)送隊(duì)列
  • BACKGROUND:如果發(fā)送事件的線程是主線程,那就將事件加入子線程的發(fā)送隊(duì)列;否則直接反射調(diào)用訂閱方法
  • ASYNC:將事件加入異步發(fā)送隊(duì)列
    反射調(diào)用訂閱方法比較簡單,直接調(diào)用invokeSubscriber(subscription, event);方法即可。
    這里主要看看三個(gè)發(fā)送隊(duì)列的實(shí)現(xiàn):
  • HandlerPoster mainThreadPoster
  • BackgroundPoster backgroundPoster
  • AsyncPoster asyncPoster
    發(fā)送隊(duì)列都實(shí)現(xiàn)了Poster接口的void enqueue(Subscription subscription, Object event);方法。

HandlerPoster mainThreadPoster

mainThreadPoster的創(chuàng)建為:new HandlerPoster(eventBus, looper, 10);。
實(shí)現(xiàn)的enqueue()方法和handleMessage()方法如下:

    @Override
    public void enqueue(Subscription subscription, Object event) {
        // 1
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            // 2
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
            while (true) {
                // 3
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                // 4
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }

注釋1處創(chuàng)建出一個(gè)PendingPost對(duì)象,PendingPost對(duì)象中包含了訂閱事件和訂閱對(duì)象,為了節(jié)省資源避免頻繁GC,使用池化的方式重復(fù)利用一組PendingPost對(duì)象。
注釋2處,將PendingPost對(duì)象加入mainThreadPoster的隊(duì)列中,然后發(fā)送一個(gè)消息(這里的消息不區(qū)分內(nèi)部的內(nèi)容,只要發(fā)送出去就會(huì)在handleMessage處理)。
注釋3處,獲取到message,就從隊(duì)列從依次彈出PendingPost對(duì)象。
注釋4處使用反射的方法執(zhí)行訂閱方法,此時(shí)執(zhí)行的方法已經(jīng)在主線程中執(zhí)行。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 前言 在上一篇文章:EventBus 3.0初探: 入門使用及其使用 完全解析中,筆者為大家介紹了EventBus...
    丶藍(lán)天白云夢(mèng)閱讀 15,982評(píng)論 21 128
  • EventBus基本使用 EventBus基于觀察者模式的Android事件分發(fā)總線。 從這個(gè)圖可以看出,Even...
    顧氏名清明閱讀 692評(píng)論 0 1
  • 先吐槽一下博客園的MarkDown編輯器,推出的時(shí)候還很高興博客園支持MarkDown了,試用了下發(fā)現(xiàn)支持不完善就...
    Ten_Minutes閱讀 651評(píng)論 0 2
  • EventBus是一個(gè)Android開源庫,其使用發(fā)布/訂閱模式,以提供代碼間的松耦合。EventBus使用中央通...
    壯少Bryant閱讀 718評(píng)論 0 4
  • 2018年12月26號(hào)又折騰了一輪,元旦是好了,生活還是混沌的樣子? 不想行尸走肉般地活著,怎么活成了愁心事。計(jì)劃...
    春雨_373c閱讀 98評(píng)論 0 1

友情鏈接更多精彩內(nèi)容