源碼解析EventBus的注冊及事件發送

最近正在學習EventBus源碼,正好總結記錄一下~

EventBus是一個針對Android優化的發布-訂閱事件總線,它簡化了應用程序內各個組件之間的通信,尤其是fragment和fragment之間的通信。優點是將發送者和接收者解耦,并且開銷小,代碼優雅。

一、EventBus的三要素

  • Event:事件,可以是任意類型的對象;
  • Subscriber:事件訂閱者,事件處理方法可以隨意取,但需要添加注解@Subscribe,并且要指定線程模型(默認POSTING);
  • Publisher:事件發布者,可以在任意線程任意位置發送事件,直接調用post()即可;
EventBus的4種線程模型:
  • POSTING(默認):發布事件和接收事件在同一個線程中,即事件在哪個線程中發布,事件處理就在哪個線程中執行;
  • MAIN:事件處理會在UI線程中執行;
  • ASYNC:事件不論在哪個線程中發布,事件處理都會在新建的子線程中執行;
  • BACKGROUND:事件在UI線程中發布,事件處理會在新建的線程中執行,事件在子線程中發布,事件處理就會在發布事件的線程中執行;

二、源碼解析

構造方法

一般我們會調用EventBus.getDefault()來獲取EventBus實例,先來看下getDefault()代碼:

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

上面代碼是一個單例模式,采用了雙重檢查模式,如果defaultInstance為空,就new一個EventBus對象,來看下EventBus()里的代碼:

    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

    public EventBus() {
        this(DEFAULT_BUILDER);
    }

this調用的是另一個構造方法:

   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;
        // builder.ignoreGeneratedIndex 是否忽略注解器生成的MyEventBusIndex
        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 是否向上查找事件的父類
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

這個方法里初始化了一些屬性,構造方法里傳入了一個EventBusBuilder,而上面的DEFAULT_BUILDER就是一個默認的EventBusBuilder,使用這個方法可以對EventBus進行配置,使用自定義參數創建EventBus實例,也可以創建默認EventBus實例。

事件發送

獲取到EventBus實例,我們調用post()方法來發送事件,來看post方法代碼:

   public void post(Object event) {
        // PostingThreadState保存著事件隊列和線程狀態信息
        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);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

首先從PostingThreadState取出事件隊列,然后將當前事件插入隊列,最后依次調用postSingleEvent()方法處理隊列中事件,并移除該事件。進入postSingleEvent()代碼:

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        // eventInheritance表示是否向上查找事件的父類,在EventBusBuilder中聲明,默認為true
        if (eventInheritance) {
            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 {
            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));
            }
        }
    }

當eventInheritance為true時,通過lookupAllEventTypes()找到所有的父類事件并存到List中,遍歷該List,調用postSingleEventForEventType()對事件進行處理。當eventInheritance為false時,直接調用postSingleEventForEventType()方法,顯而易見,最后都走到這個postSingleEventForEventType()方法,我們來看源碼:

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        // 同步取出訂閱對象集合
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            // 遍歷集合,將事件event和訂閱對象subscription賦值給postingState
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                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;
    }

同步取出訂閱對象集合subscriptions,遍歷subscriptions,將事件event和訂閱對象subscription賦值給postingState,然后調用postToSubscription(),我們再看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:
                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);
        }
    }

這個方法里取出了訂閱方法的線程模型,根據線程模型來分別處理:

  1. 如果線程模型是POSTING,就通過反射直接運行訂閱的方法;
  2. 如果線程模型是MAIN,提交事件的是主線程,就通過反射直接運行訂閱的方法,如果不是主線程,則通過mainThreadPoster將訂閱事件添加到主線程隊列里面;
  3. 如果線程模型是BACKGROUND,提交事件的是主線程,則通過backgroundPoster將訂閱事件添加到子線程隊列里面,如果不是主線程,就通過反射直接運行訂閱的方法;
  4. 如果線程模型是ASYNC,就通過asyncPoster將訂閱事件添加到子線程隊列里面;
    這就和我們上面提到的4種線程模型對上了~
事件注冊

我們發送了事件,想要接收事件的話,需要先調用register()注冊,源碼如下:

   public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        // 獲取訂閱者訂閱方法集合
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            // 遍歷訂閱者方法集合,注冊訂閱者
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

register一共做了兩件事:通過findSubscriberMethods()查找訂閱者訂閱方法集合subscriberMethods,以及遍歷subscriberMethods集合,調用subscribe()進行訂閱者的注冊。

findSubscriberMethods()

我們先來看findSubscriberMethods()方法,源碼如下:

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // 從緩存中獲取訂閱者方法集合
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        // ignoreGeneratedIndex默認false,在EventBusBuilder中聲明,表示是否忽略注解器生成的MyEventBusIndex
        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;
        }
    }

這個方法先從緩存中獲取訂閱者方法集合subscriberMethods,如果不為空,直接返回,如果為空就通過ignoreGeneratedIndex這個變量判斷調用哪個方法,ignoreGeneratedIndex默認false,所以會調用findUsingInfo()方法獲取訂閱者方法集合subscriberMethods,拿到集合后將其放入緩存中。我們再看findUsingInfo()方法:

   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();
        }
        // 回收findState并返回訂閱方法集合
        return getMethodsAndRelease(findState);
    }

首先調用prepareFindState()初始化findState,通過getSubscriberInfo()方法獲取訂閱者信息subscriberInfo,獲取到信息后調用getSubscriberMethods()獲取訂閱方法相關信息,遍歷相關信息,向訂閱方法集合subscriberMethods中添加訂閱方法對象subscriberMethod,最后調用getMethodsAndRelease()回收findState并返回訂閱方法集合;如果沒有獲取到訂閱者信息subscriberInfo,調用 findUsingReflectionInSingleClass()。

    private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
            // This is faster than getMethods, especially when subscribers are fat classes like Activities
            // 通過反射獲取訂閱者中所有方法
            methods = findState.clazz.getDeclaredMethods();
        } catch (Throwable th) {
            // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
            methods = findState.clazz.getMethods();
            findState.skipSuperClasses = true;
        }
        for (Method method : methods) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                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中
                            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");
            }
        }
    }

調用getDeclaredMethods()通過反射獲取訂閱者中所有方法,遍歷所有方法,根據方法類型、參數、注解找到訂閱方法,將訂閱方法保存到findState中。

subscribe()
    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        // 創建訂閱對象newSubscription
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        // 根據事件類型eventType獲取訂閱對象集合subscriptions
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            // 將訂閱對象集合subscriptions保存到Map集合subscriptionsByEventType中
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            // 判斷訂閱者是否已經被注冊
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                // 按照優先級將newSubscription插入訂閱對象集合subscriptions中
                subscriptions.add(i, newSubscription);
                break;
            }
        }
        // 通過訂閱者subscriber獲取事件類型集合subscribedEvents
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            // 將subscribedEvents存到Map集合typesBySubscriber中
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        // 將事件類型eventType放入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()主要做了兩件事:一件是將訂閱對象集合subscriptions保存到Map集合subscriptionsByEventType中,將事件類型集合subscribedEvents保存到Map集合typesBySubscriber中;一件是對黏性事件的處理。

事件取消注冊

取消注冊調用unregister()方法,代碼如下:

    /** Unregisters the given subscriber from all event classes. */
    public synchronized void unregister(Object subscriber) {
        // 通過訂閱者subscriber找到事件類型集合subscribedTypes
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            // 將訂閱者subscriber對應的事件類型從集合中移除
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

先獲取事件類型集合subscribedTypes,遍歷該集合,調用unsubscribeByEventType()方法,并將訂閱者subscriber對應的事件類型從集合subscribedTypes中移除。unsubscribeByEventType()代碼:

    /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
         // 獲取對應的訂閱對象集合subscriptions
        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);
                // 訂閱對象的subscriber屬性等于傳進來的subscriber
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    // 移除該訂閱對象
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

到這,EventBus的源碼基本完活啦~

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

推薦閱讀更多精彩內容