EventBus原理解析

EventBus是一個Android開源庫,其使用發布/訂閱模式,以提供代碼間的松耦合。EventBus使用中央通信方式,僅僅使用幾行簡單的代碼,就可以達到解耦代碼的目的。從而,簡化代碼,移除依賴,加快APP的開發速度。下邊是官方的 EventBus 原理圖:

1、先說說優點:

  • 簡化組件之間的通信
  • 解耦事件的發送者和接收者
  • 很好的應用于Activity之間,Fragment之間,后臺線程之間的通信,避免使用intent或者handler所帶來的復雜度
  • 可以避免復雜的,易于出錯的依賴和生命周期問題
  • 速度快,尤其是在做了優化之后
  • 輕量 (大概 50k 的jar包)
  • 有諸多高級特性,例如多種類型的線程模式,subscriber的優先級,等等

2、EventBus特性

  • 簡單易用的基于注解的API:簡單地把@Subscribe注解放在你的訂閱方法前面即可。通過編譯期的訂閱者索引,app不需要在運行期做注解反射。
  • 支持事件投遞到Android主線程:當訂閱者需要和UI做交互的時候,EventBus能發送事件到主線程中去,而不管該事件是從哪個線程中發出來的。
  • 支持事件投遞到后臺線程:當訂閱者需要做耗時任務時,EventBus能發送事件到后臺線程中去,避免阻塞主線程。
  • 支持事件&訂閱者繼承關系:在EventBus中,面向對象也被應用到事件和訂閱者類中。例如,事件類A是事件類B的父類,這時,發送B類型的事件,該事件也會發送給對于事件類A感興趣的訂閱者。對于訂閱者類,也存在相似的繼承關系。
  • 零設定即可使用:不需要任何設定,在你代碼的任何地方,使用一個現成的默認的EventBus實例對象,你就可以開始工作了。
  • 可配置:使用建造者模式,你可以調整EventBus的行為,使之滿足你的需求。

1、Subscribe注解

EventBus通過使用注解的方式,配置事件訂閱方法,例如:

@Subscribe
public void handleEvent(String event) {
    // do something
}

其中事件類型可以是 Java 中已有的類型或者我們自定義的類型。 具體看下Subscribe注解的實現:

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
    // 指定事件訂閱方法的線程模式,即在那個線程執行事件訂閱方法處理事件,默認為POSTING
    ThreadMode threadMode() default ThreadMode.POSTING;
    // 是否支持粘性事件,默認為false
    boolean sticky() default false;
    // 指定事件訂閱方法的優先級,默認為0,如果多個事件訂閱方法可以接收相同事件的,則優先級高的先接收到事件
    int priority() default 0;
}

所以在使用Subscribe注解時可以根據需求指定threadMode、sticky、priority三個屬性。

其中threadMode屬性有如下幾個可選值:

  • ThreadMode.POSTING,默認的線程模式,在哪個線程發送事件就在哪個線程處理事件,避免了線程切換,效率高。訂閱方法最好不要執行耗時操作,因為它可能會影響發送者的線程,尤其是主線程的時候

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

  • ThreadMode.BACKGROUND,訂閱方法執行在單一的一個子線程。如果在主線程發送事件,則先將事件入隊列,然后通過線程池依次處理事件;如果在子線程發送事件,則直接在發送事件的線程處理事件。

  • ThreadMode.ASYNC,訂閱方法會在一個新開的子線程(不是主線程、也不是發送者所在線程)執行(類似每次都新建一個線程),在執行耗時操作時需要使用這個,不會影響其他線程,但是要控制數量,避免創建大量線程導致的開銷,EventBus 使用線程池控制

2 注冊事件訂閱方法

注冊事件的方式如下:

EventBus.getDefault().register(this);

其中getDefault()是一個單例方法,保證當前只有一個EventBus實例:

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

繼續看new EventBus()做了些什么:

public EventBus() {
        this(DEFAULT_BUILDER);
    }

在這里又調用了EventBus的另一個構造函數來完成它相關屬性的初始化:

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

DEFAULT_BUILDER就是一個默認的EventBusBuilder

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

如果有需要的話,我們也可以通過配置EventBusBuilder來更改EventBus的屬性,例如用如下方式注冊事件:

EventBus.builder()
        .eventInheritance(false)
        .logSubscriberExceptions(false)
        .build()
        .register(this);

有了EventBus的實例就可以進行注冊了:

public void register(Object subscriber) {
        // 得到當前要注冊類的Class對象
        Class<?> subscriberClass = subscriber.getClass();
        // 根據Class查找當前類中訂閱了事件的方法集合,即使用了Subscribe注解、有public修飾符、一個參數的方法
        // SubscriberMethod類主要封裝了符合條件方法的相關信息:
        // Method對象、線程模式、事件類型、優先級、是否是粘性事等
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            // 循環遍歷訂閱了事件的方法集合,以完成注冊
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

可以看到register()方法主要分為查找和注冊兩部分,首先來看查找的過程,從findSubscriberMethods()開始:

2.1 查找過程

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // METHOD_CACHE是一個ConcurrentHashMap,直接保存了subscriberClass和對應SubscriberMethod的集合,以提高注冊效率,賦值重復查找。
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        // 由于使用了默認的EventBusBuilder,則ignoreGeneratedIndex屬性默認為false,即是否忽略注解生成器
        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;
        }
    }

findSubscriberMethods()流程很清晰,即先從緩存中查找,如果找到則直接返回,否則去做下一步的查找過程,然后緩存查找到的集合,根據上邊的注釋可知findUsingInfo()方法會被調用:

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        // 初始狀態下findState.clazz就是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.clazz為subscriberClass的父類Class,即需要遍歷父類
            findState.moveToSuperclass();
        }
        // 查找到的方法保存在了FindState實例的subscriberMethods集合中。
        // 使用subscriberMethods構建一個新的List<SubscriberMethod>
        // 釋放掉findState
        return getMethodsAndRelease(findState);
    }

findUsingInfo()方法會在當前要注冊的類以及其父類中查找訂閱事件的方法,這里出現了一個FindState類,它是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();
            // 如果是public類型,但非abstract、static等
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                // 獲得當前方法所有參數的類型
                Class<?>[] parameterTypes = method.getParameterTypes();
                // 如果當前方法只有一個參數
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    // 如果當前方法使用了Subscribe注解
                    if (subscribeAnnotation != null) {
                        // 得到該參數的類型
                        Class<?> eventType = parameterTypes[0];
                        // checkAdd()方法用來判斷FindState的anyMethodByEventType map是否已經添加過以當前eventType為key的鍵值對,沒添加過則返回true
                        if (findState.checkAdd(method, eventType)) {
                             // 得到Subscribe注解的threadMode屬性值,即線程模式
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            // 創建一個SubscriberMethod對象,并添加到subscriberMethods集合
                            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");
            }
        }
    }

到此register()方法中findSubscriberMethods()流程就分析完了,我們已經找到了當前注冊類及其父類中訂閱事件的方法的集合。接下來分析具體的注冊流程,即register()中的subscribe()方法:

2.2 訂閱方法

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        // 得到當前訂閱了事件的方法的參數類型
        Class<?> eventType = subscriberMethod.eventType;
        // Subscription類保存了要注冊的類對象以及當前的subscriberMethod
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        // subscriptionsByEventType是一個HashMap,保存了以eventType為key,Subscription對象集合為value的鍵值對
        // 先查找subscriptionsByEventType是否存在以當前eventType為key的值
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        // 如果不存在,則創建一個subscriptions,并保存到subscriptionsByEventType
        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);
            }
        }
        // 添加上邊創建的newSubscription對象到subscriptions中
        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;
            }
        }
        // typesBySubscribere也是一個HashMap,保存了以當前要注冊類的對象為key,注冊類中訂閱事件的方法的參數類型的集合為value的鍵值對
        // 查找是否存在對應的參數類型集合
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        // 不存在則創建一個subscribedEvents,并保存到typesBySubscriber
        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);
            }
        }
    }

這就是注冊的核心流程,所以subscribe()方法主要是得到了subscriptionsByEventType、typesBySubscriber兩個 HashMap。我們在發送事件的時候要用到subscriptionsByEventType,完成事件的處理。當取消 EventBus 注冊的時候要用到typesBySubscriber、subscriptionsByEventType,完成相關資源的釋放。

3、取消注冊

接下來看,EventBus 如何取消注冊:

EventBus.getDefault().unregister(this);

核心的方法就是unregister():

public synchronized void unregister(Object subscriber) {
        // 得到當前注冊類對象 對應的 訂閱事件方法的參數類型 的集合
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            // 遍歷參數類型集合,釋放之前緩存的當前類中的Subscription
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            // 刪除以subscriber為key的鍵值對
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

內容很簡單,繼續看unsubscribeByEventType()方法:

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        // 得到當前參數類型對應的Subscription集合
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            // 遍歷Subscription集合
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                // 如果當前subscription對象對應的注冊類對象 和 要取消注冊的注冊類對象相同,則刪除當前subscription對象
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

所以在unregister()方法中,釋放了typesBySubscriber、subscriptionsByEventType中緩存的資源。

4、發送事件

當發送一個事件的時候,我們可以通過如下方式:

EventBus.getDefault().post("Hello World!")

可以看到,發送事件就是通過post()方法完成的:

public void post(Object event) {
        // currentPostingThreadState是一個PostingThreadState類型的ThreadLocal
        // PostingThreadState類保存了事件隊列和線程模式等信息
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        // 將要發送的事件添加到事件隊列
        eventQueue.add(event);
        // isPosting默認為false
        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()) {
                    // 發送單個事件
                    // eventQueue.remove(0),從事件隊列移除事件
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

所以post()方法先將發送的事件保存的事件隊列,然后通過循環出隊列,將事件交給postSingleEvent()方法處理:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        // eventInheritance默認為true,表示是否向上查找事件的父類
        if (eventInheritance) {
            // 查找當前事件類型的Class,連同當前事件類型的Class保存到集合
            List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
            int countTypes = eventTypes.size();
            // 遍歷Class集合,繼續處理事件
            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) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

postSingleEvent()方法中,根據eventInheritance屬性,決定是否向上遍歷事件的父類型,然后用postSingleEventForEventType()方法進一步處理事件:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 獲取事件類型對應的Subscription集合
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        // 如果已訂閱了對應類型的事件
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                // 記錄事件
                postingState.event = event;
                // 記錄對應的subscription
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                    // 最終的事件處理
                    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;
    }

postSingleEventForEventType()方法核心就是遍歷發送的事件類型對應的Subscription集合,然后調用postToSubscription()方法處理事件。

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 {
                     // 如果是在子線程發送事件,則將事件入隊列,通過Handler切換到主線程執行處理事件
                    // mainThreadPoster 不為空
                    mainThreadPoster.enqueue(subscription, event);
                }
                break;
            // 無論在那個線程發送事件,都先將事件入隊列,然后通過 Handler 切換到主線程,依次處理事件。
            // mainThreadPoster 不為空
            case MAIN_ORDERED:
                if (mainThreadPoster != null) {
                    mainThreadPoster.enqueue(subscription, event);
                } else {
                    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);
        }
    }

可以看到,postToSubscription()方法就是根據訂閱事件方法的線程模式、以及發送事件的線程來判斷如何處理事件,至于處理方式主要有兩種:
一種是在相應線程直接通過invokeSubscriber()方法,用反射來執行訂閱事件的方法,這樣發送出去的事件就被訂閱者接收并做相應處理了:

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

另外一種是先將事件入隊列(其實底層是一個List),然后做進一步處理,我們以mainThreadPoster.enqueue(subscription, event)為例簡單的分析下,其中mainThreadPoster是HandlerPoster類的一個實例,來看該類的主要實現:

public class HandlerPoster extends Handler implements Poster {
    private final PendingPostQueue queue;
    private boolean handlerActive;
    ......
    public void enqueue(Subscription subscription, Object event) {
        // 用subscription和event封裝一個PendingPost對象
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            // 入隊列
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                // 發送開始處理事件的消息,handleMessage()方法將被執行,完成從子線程到主線程的切換
                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) {
                // 出隊列
                PendingPost pendingPost = queue.poll();
                ......
                // 進一步處理pendingPost
                eventBus.invokeSubscriber(pendingPost);
                ......
            }
        } finally {
            handlerActive = rescheduled;
        }
    }
}

所以HandlerPoster的enqueue()方法主要就是將subscription、event對象封裝成一個PendingPost對象,然后保存到隊列里,之后通過Handler切換到主線程,在handleMessage()方法將中將PendingPost對象循環出隊列,交給invokeSubscriber()方法進一步處理:

void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        // 釋放pendingPost引用的資源
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            // 用反射來執行訂閱事件的方法
            invokeSubscriber(subscription, event);
        }
    }

這個方法很簡單,主要就是從pendingPost中取出之前保存的event、subscription,然后用反射來執行訂閱事件的方法,又回到了第一種處理方式。所以mainThreadPoster.enqueue(subscription, event)的核心就是先將將事件入隊列,然后通過Handler從子線程切換到主線程中去處理事件。

backgroundPoster.enqueue()和asyncPoster.enqueue也類似,內部都是先將事件入隊列,然后再出隊列,但是會通過線程池去進一步處理事件。

6、粘性事件

一般情況,我們使用 EventBus 都是準備好訂閱事件的方法,然后注冊事件,最后在發送事件,即要先有事件的接收者。但粘性事件卻恰恰相反,我們可以先發送事件,后續再準備訂閱事件的方法、注冊事件。

由于這種差異,我們分析粘性事件原理時,先從事件發送開始,發送一個粘性事件通過如下方式:

EventBus.getDefault().postSticky("Hello World!");

來看postSticky()方法是如何實現的:

public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        post(event);
    }

postSticky()方法主要做了兩件事,先將事件類型和對應事件保存到stickyEvents中,方便后續使用;然后執行post(event)繼續發送事件,這個post()方法就是之前發送的post()方法。所以,如果在發送粘性事件前,已經有了對應類型事件的訂閱者,及時它是非粘性的,依然可以接收到發送出的粘性事件。

發送完粘性事件后,再準備訂閱粘性事件的方法,并完成注冊。核心的注冊事件流程還是我們之前的register()方法中的subscribe()方法,前邊分析subscribe()方法時,有一段沒有分析的代碼,就是用來處理粘性事件的:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        ......
        ......
        ......
        // 如果當前訂閱事件的方法的Subscribe注解的sticky屬性為true,即該方法可接受粘性事件
        if (subscriberMethod.sticky) {
            // 默認為true,表示是否向上查找事件的父類
            if (eventInheritance) {
                // stickyEvents就是發送粘性事件時,保存了事件類型和對應事件
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();
                    // 如果candidateEventType是eventType的子類或
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        // 獲得對應的事件
                        Object stickyEvent = entry.getValue();
                        // 處理粘性事件
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

可以看到,處理粘性事件就是在 EventBus 注冊時,遍歷stickyEvents,如果當前要注冊的事件訂閱方法是粘性的,并且該方法接收的事件類型和stickyEvents中某個事件類型相同或者是其父類,則取出stickyEvents中對應事件類型的具體事件,做進一步處理。繼續看checkPostStickyEventToSubscription()處理方法:

private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            postToSubscription(newSubscription, stickyEvent, isMainThread());
        }
    }

最終還是通過postToSubscription()方法完成粘性事件的處理,這就是粘性事件的整個處理流程。

7、Subscriber Index

回顧之前分析的 EventBus 注冊事件流程,主要是在項目運行時通過反射來查找訂事件的方法信息,這也是默認的實現,如果項目中有大量的訂閱事件的方法,必然會對項目運行時的性能產生影響。其實除了在項目運行時通過反射查找訂閱事件的方法信息,EventBus 還提供了在項目編譯時通過注解處理器查找訂閱事件方法信息的方式,生成一個輔助的索引類來保存這些信息,這個索引類就是Subscriber Index,其實和 ButterKnife 的原理類似。

要在項目編譯時查找訂閱事件的方法信息,首先要在 app 的 build.gradle 中加入如下配置:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                // 根據項目實際情況,指定輔助索引類的名稱和包名
                arguments = [ eventBusIndex : 'com.shh.sometest.MyEventBusIndex' ]
            }
        }
    }
}
dependencies {
    compile 'org.greenrobot:eventbus:3.1.1'
    // 引入注解處理器
    annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}

然后在項目的 Application 中添加如下配置,以生成一個默認的 EventBus 單例:

EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();

之后的用法就和我們平時使用 EventBus 一樣了。當項目編譯時會在生成對應的MyEventBusIndex類:

對應的源碼如下:

public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(MainActivity.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("changeText", String.class),
        }));

    }

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

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}

其中SUBSCRIBER_INDEX是一個HashMap,保存了當前注冊類的 Class 類型和其中事件訂閱方法的信息。

接下來分析下使用 Subscriber Index 時 EventBus 的注冊流程,我們先分析:

EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();

首先創建一個EventBusBuilder,然后通過addIndex()方法添加索引類的實例:

public EventBusBuilder addIndex(SubscriberInfoIndex index) {
        if (subscriberInfoIndexes == null) {
            subscriberInfoIndexes = new ArrayList<>();
        }
        subscriberInfoIndexes.add(index);
        return this;
    }

即把生成的索引類的實例保存在subscriberInfoIndexes集合中,然后用installDefaultEventBus()創建默認的 EventBus實例:

public EventBus installDefaultEventBus() {
        synchronized (EventBus.class) {
            if (EventBus.defaultInstance != null) {
                throw new EventBusException("Default instance already exists." +
                        " It may be only set once before it's used the first time to ensure consistent behavior.");
            }
            EventBus.defaultInstance = build();
            return EventBus.defaultInstance;
        }
    }
public EventBus build() {
        // this 代表當前EventBusBuilder對象
        return new EventBus(this);
    }

即用當前EventBusBuilder對象創建一個 EventBus 實例,這樣我們通過EventBusBuilder配置的 Subscriber Index 也就傳遞到了EventBus實例中,然后賦值給EventBus的 defaultInstance成員變量。之前我們在分析 EventBus 的getDefault()方法時已經見到了defaultInstance:

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

所以在 Application 中生成了 EventBus 的默認單例,這樣就保證了在項目其它地方執行EventBus.getDefault()就能得到唯一的 EventBus 實例!之前在分析注冊流程時有一個 方法findUsingInfo():

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            // 查找SubscriberInfo
            findState.subscriberInfo = getSubscriberInfo(findState);
            // 條件成立
            if (findState.subscriberInfo != null) {
                // 獲得當前注冊類中所有訂閱了事件的方法
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    // findState.checkAdd()之前已經分析過了,即是否在FindState的anyMethodByEventType已經添加過以當前eventType為key的鍵值對,沒添加過返回true
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        // 將subscriberMethod對象添加到subscriberMethods集合
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

由于我們現在使用了 Subscriber Index 所以不會通過findUsingReflectionInSingleClass()來反射解析訂閱事件的方法。我們重點來看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) {
                // 根據注冊類的 Class 類查找SubscriberInfo
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }

subscriberInfoIndexes就是在前邊addIndex()方法中創建的,保存了項目中的索引類實例,即MyEventBusIndex的實例,繼續看索引類的getSubscriberInfo()方法,來到了MyEventBusIndex類中:

@Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }

即根據注冊類的 Class 類型從 SUBSCRIBER_INDEX 查找對應的SubscriberInfo,如果我們在注冊類中定義了訂閱事件的方法,則 info不為空,進而上邊findUsingInfo()方法中findState.subscriberInfo != null成立,到這里主要的內容就分析完了,其它的和之前的注冊流程一樣。
所以 Subscriber Index 的核心就是項目編譯時使用注解處理器生成保存事件訂閱方法信息的索引類,然后項目運行時將索引類實例設置到 EventBus 中,這樣當注冊 EventBus 時,從索引類取出當前注冊類對應的事件訂閱方法信息,以完成最終的注冊,避免了運行時反射處理的過程,所以在性能上會有質的提高。項目中可以根據實際的需求決定是否使用 Subscriber Index。

這里提一句,使用這種方式,會在查找過程中,使用索引的方式添加subscriberMethods,避免了反射使用clazz.getDeclaredMethods();方式,從而提升了性能,但是post過程,最終調用,還是會method.invoke()的方式來調用方法。

而且clazz.getDeclaredMethods()耗時會比method.invoke()多一些,大約在2:1的時間,當然,如果次數少的話,沒啥差別,如果次數多了,就會有影響。之前做過實驗,調用100萬次的話,clazz.getMethods()是3242ms,method.invoke()是1632ms。

8 小結

結合上邊的分析,我們可以總結出register、post、unregister的核心流程:

到這里 EventBus 幾個重要的流程就分析完了,整體的設計思路還是值得我們學習的。和 Android 自帶的廣播相比,使用簡單、同時又兼顧了性能。但如果在項目中濫用的話,各種邏輯交叉在一起,也可能會給后期的維護帶來困難。



聲明:此文章為本人學習筆記,參考于:https://juejin.im/post/5ae2e6dcf265da0b9d77f28e#heading-1

如果您覺得有用,歡迎關注我的公眾號,我會不定期發布自己的學習筆記、資料、以及感悟,歡迎留言,與大家一起探索AI之路。

AI探索之路
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。