EventBus 3.0進階:源碼及其設計模式 完全解析

本文導讀

由于EventBus較為復雜,因此本文也相當長,所以本文分為以下幾個部分:創建、注冊、發送事件、關于粘性事件的解析、以及最后的思考。讀者可以有選擇性地選取某部分來進行閱讀。

實現原理

創建

上一篇文章提到,要想注冊成為訂閱者,必須在一個類中調用如下:

EventBus.getDefault().register(this);

那么,我們看一下getDefault()的源碼是怎樣的, EventBus#getDefault()

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

可以看出,這里使用了 單例模式 ,而且是雙重校驗的單例,確保在不同線程中也只存在一個EvenBus的實例。

單例模式:一個類有且僅有一個實例,并且自行實例化向整個系統提供。

然而,我們看看EventBus的構造方法:

/**

  • Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
  • central bus, consider {@link #getDefault()}. */ public EventBus() { this(DEFAULT_BUILDER); }</code></pre>

    它的構造方法并沒有設置成私有的!這是為什么?從注解我們看到,每一個EventBus都是獨立地、處理它們自己的事件,因此可以存在多個EventBus,而 通過getDefault()方法獲取的實例,則是它已經幫我們構建好的EventBus,是單例,無論在什么時候通過這個方法獲取的實例都是同一個實例 。除此之外,我們可以通過建造者幫我們建造具有不同功能的EventBus。

    我們繼續看上面的this(DEFAULT_BUILDER)調用了另一個構造方法:

    EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
    backgroundPoster = new BackgroundPoster(this);
    asyncPoster = new AsyncPoster(this);
    //一系列的builder賦值
    }

    可以看出,對成員變量進行了一系列的初始化,那么我們來看看幾個關鍵的成員變量:

    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    private final Map<Class<?>, Object> stickyEvents;

    subscriptionsByEventType:以event(即事件類)為key,以訂閱列表(Subscription)為value,事件發送之后,在這里尋找訂閱者,而Subscription又是一個CopyOnWriteArrayList,這是一個線程安全的容器。你們看會好奇,Subscription到底是什么,其實看下去就會了解的,現在先提前說下:Subscription是一個封裝類,封裝了訂閱者、訂閱方法這兩個類。

    typesBySubscriber:以訂閱者類為key,以event事件類為value,在進行register或unregister操作的時候,會操作這個map。

    stickyEvents:保存的是粘性事件,粘性事件上一篇文章有詳細描述。

    回到EventBus的構造方法,接下來實例化了三個Poster,分別是mainThreadPoster、backgroundPoster、asyncPoster等,這三個Poster是用來處理粘性事件的,我們下面會展開講述。接著,就是對builder的一系列賦值了,這里使用了 建造者模式

    建造者模式:將一個復雜對象的構造與它的表示分離,使同樣的構建過程可以創建不同的表示。

    這里的建造者是 EventBusBuilder ,它的一系列方法用于配置EventBus的屬性,使用getDefault()方法獲取的實例,會有著默認的配置,上面說過,EventBus的構造方法是公有的,所以我們可以通過給EventBusBuilder設置不同的屬性,進而獲取有著不同功能的EventBus。那么我們來列舉幾個常用的屬性加以講解:

    //默認地,EventBus會考慮事件的超類,即事件如果繼承自超類,那么該超類也會作為事件發送給訂閱者。
    //如果設置為false,則EventBus只會考慮事件類本身。
    boolean eventInheritance = true;
    public EventBusBuilder eventInheritance(boolean eventInheritance) {
    this.eventInheritance = eventInheritance;
    return this;
    }

//當訂閱方法是以onEvent開頭的時候,可以調用該方法來跳過方法名字的驗證,訂閱這類會保存在List中 List<Class<?>> skipMethodVerificationForClasses; public EventBusBuilder skipMethodVerificationFor(Class<?> clazz) { if (skipMethodVerificationForClasses == null) { skipMethodVerificationForClasses = new ArrayList<>(); } skipMethodVerificationForClasses.add(clazz); return this; }

//更多的屬性配置請參考源碼,均有注釋 //...</code></pre>

那么,我們通過建造者模式來手動創建一個EventBus,而不是使用getDefault()方法:

EventBus eventBus = EventBus.builder()
        .eventInheritance(false)
        .sendNoSubscriberEvent(true)
        .skipMethodVerificationFor(MainActivity.class)
        .build();

注冊

好了,以上說了一大推關于EventBus的創建,接下來,我們繼續講它的注冊過程。要想使一個類成為訂閱者,那么這個類必須有一個訂閱方法,以@Subscribe注解標記的方法,接著調用register()方法來進行注冊。那么我們直接來看 EventBus#register()

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

先獲取了訂閱者類的class,接著交給SubscriberMethodFinder.findSubscriberMethods()處理,返回結果保存在List<SubscriberMethod>中,由此可推測通過上面的方法把訂閱方法找出來了,并保存在集合中,那么我們直接看這個方法, SubscriberMethodFinder#findSubscriberMethods()

findSubscriberMethods

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    //首先從緩存中取出subscriberMethodss,如果有則直接返回該已取得的方法
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //從EventBusBuilder可知,ignoreGenerateIndex一般為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 {
    //將獲取的subscriberMeyhods放入緩存中
    METHOD_CACHE.put(subscriberClass, subscriberMethods);
    return subscriberMethods;
}

}</code></pre>

從上面的邏輯可以知道,一般會調用findUsingInfo方法,我們接著看 SubscriberMethodFinder#findUsingInfo 方法:

findUsingInfo

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    //準備一個FindState,該FindState保存了訂閱者類的信息
    FindState findState = prepareFindState();
    //對FindState初始化
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //獲得訂閱者的信息,一開始會返回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 {
            //1 、到了這里
            findUsingReflectionInSingleClass(findState);
        }
        //移動到父類繼續查找
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

上面用到了FindState這個內部類來保存訂閱者類的信息,我們看看它的內部結構:

FindState

static class FindState {
    //訂閱方法的列表
    final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
    //以event為key,以method為value
    final Map<Class, Object> anyMethodByEventType = new HashMap<>();
    //以method的名字生成一個method為key,以訂閱者類為value
    final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
    final StringBuilder methodKeyBuilder = new StringBuilder(128);

Class<?> subscriberClass;
Class<?> clazz;
boolean skipSuperClasses;
SubscriberInfo subscriberInfo;

//對FindState初始化
void initForSubscriber(Class<?> subscriberClass) {
    this.subscriberClass = clazz = subscriberClass;
    skipSuperClasses = false;
    subscriberInfo = null;
}

//省略...

}</code></pre>

可以看出,該內部類保存了訂閱者及其訂閱方法的信息,用Map一一對應進行保存,接著利用initForSubscriber進行初始化,這里subscriberInfo初始化為null,因此在 SubscriberMethodFinder#findUsingInfo 里面,會直接調用到①號代碼,即調用 SubscriberMethodFinder#findUsingReflectionInSingleClass ,這個方法非常重要!!!在這個方法內部,利用反射的方式,對訂閱者類進行掃描,找出訂閱方法,并用上面的Map進行保存,我們來看這個方法。

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注解
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    //參數類型 即為 事件類型
                    Class<?> eventType = parameterTypes[0];
                    // 2 、調用checkAdd方法
                    if (findState.checkAdd(method, eventType)) {
                        //從注解中提取threadMode
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        //新建一個SubscriberMethod對象,并添加到findState的subscriberMethods這個集合內
                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                    }
                }
            //如果開啟了嚴格驗證,同時當前方法又有@Subscribe注解,對不符合要求的方法會拋出異常
            } 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");
        }
    }
}

雖然該方法比較長,但是邏輯非常清晰,逐一判斷訂閱者類是否存在訂閱方法,如果符合要求,并且②號代碼調用 FindState#checkAdd 方法返回true的時候,才會把方法保存在findState的subscriberMethods內。而SubscriberMethod則是用于保存訂閱方法的一個類。那么我們來看看 FindState#checkAdd 做了什么工作。

checkAdd

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

從注釋可知,這里包含兩重檢驗,第一層檢驗是判斷eventType的類型,而第二次檢驗是判斷方法的完整簽名。首先通過anyMethodByEventType.put(eventType, method) 將eventType以及method放進anyMethodByEventType這個Map中(上面提到),同時該put方法會返回同一個key的上一個value值,所以如果之前沒有別的方法訂閱了該事件,那么existing應該為null,可以直接返回true;否則為某一個訂閱方法的實例,要進行下一步的判斷。接著往下走,會調用 checkAddWithMethodSignature() 方法。

checkAddWithMethodSignature

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

//methodKey由方法名與事件名組成
String methodKey = methodKeyBuilder.toString();
//獲取當前方法所在的類的類名
Class<?> methodClass = method.getDeclaringClass();
//給subscriberClassByMethodKey賦值,并返回上一個相同key的 類名
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;
}

}</code></pre>

從上面的代碼看出,該方法首先獲取了當前方法的methodKey、methodClass等,并賦值給subscriberClassByMethodKey,如果方法簽名相同,那么返回舊值給methodClassOld,接著是一個if判斷,判斷methodClassOld是否為空,由于第一次調用該方法的時候methodClassOld肯定是null,此時就可以直接返回true了。但是,后面還有一個判斷即 methodClassOld.isAssignableFrom(methodClass) ,這個的意思是:methodClassOld是否是methodClass的父類或者同一個類。如果這兩個條件都不滿足,則會返回false,那么當前方法就不會添加為訂閱方法了。

那么,說了一大堆關于 checkAddcheckAddWithMethodSignature 方法的源碼,那么這兩個方法到底有什么作用呢?從這兩個方法的邏輯來看,第一層判斷根據eventType來判斷是否有多個方法訂閱該事件,而第二層判斷根據完整的方法簽名(包括方法名字以及參數名字)來判斷。下面是筆者的理解:

第一種情況:比如一個類有多個訂閱方法,方法名不同,但它們的參數類型都是相同的(雖然一般不這樣寫,但不排除這樣的可能),那么遍歷這些方法的時候,會多次調用到checkAdd方法,由于existing不為null,那么會進而調用checkAddWithMethodSignature方法,但是由于每個方法的名字都不同,因此methodClassOld會一直為null,因此都會返回true。也就是說, 允許一個類有多個參數相同的訂閱方法

第二種情況:類B繼承自類A,而每個類都是有相同訂閱方法,換句話說,類B的訂閱方法繼承并重寫自類A,它們都有著一樣的方法簽名。方法的遍歷會從子類開始,即B類,在checkAddWithMethodSignature方法中,methodClassOld為null,那么B類的訂閱方法會被添加到列表中。接著,向上找到類A的訂閱方法,由于methodClassOld不為null而且顯然類B不是類A的父類,methodClassOld.isAssignableFrom(methodClass)也會返回false,那么會返回false。也就是說, 子類繼承并重寫了父類的訂閱方法,那么只會把子類的訂閱方法添加到訂閱者列表,父類的方法會忽略 。

讓我們回到findUsingReflectionInSingleClass方法,當遍歷完當前類的所有方法后,會回到 findUsingInfo 方法,接著會執行最后一行代碼,即return getMethodsAndRelease(findState);那么我們繼續看 SubscriberMethodFinder#getMethodsAndRelease 方法。

getMethodsAndRelease

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
    //從findState獲取subscriberMethods,放進新的ArrayList
    List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
    //把findState回收
    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;
}

通過該方法,把subscriberMethods不斷逐層返回,直到返回 EventBus#register() 方法,最后開始遍歷每一個訂閱方法,并調用subscribe(subscriber, subscriberMethod)方法,那么,我們繼續來看 EventBus#subscribe 方法。

subscribe

在該方法內,主要是實現訂閱方法與事件直接的關聯,即注冊,即放進我們上面提到關鍵的幾個Map中:subscriptionsByEventType、typesBySubscriber、stickyEvents。

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    //將subscriber和subscriberMethod封裝成 Subscription
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //根據事件類型獲取特定的 Subscription
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    //如果為null,說明該subscriber尚未注冊該事件
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<>();
        subscriptionsByEventType.put(eventType, subscriptions);
    } else {
        //如果不為null,并且包含了這個subscription 那么說明該subscriber已經注冊了該事件,拋出異常
        if (subscriptions.contains(newSubscription)) {
            throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "

                + eventType);
    }
}

//根據優先級來設置放進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;
    }
}

//根據subscriber(訂閱者)來獲取它的所有訂閱事件
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
    subscribedEvents = new ArrayList<>();
    //把訂閱者、事件放進typesBySubscriber這個Map中
    typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);

//下面是對粘性事件的處理
if (subscriberMethod.sticky) {
    //從EventBusBuilder可知,eventInheritance默認為true.
    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 {
        //根據eventType,從stickyEvents列表中獲取特定的事件
        Object stickyEvent = stickyEvents.get(eventType);
        //分發事件
        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
    }
}

}</code></pre>

到目前為止,注冊流程基本分析完畢,而關于最后的粘性事件的處理,這里暫時不說,下面會詳細進行講述。可以看出,整個注冊流程非常地長,方法的調用棧很深,在各個方法中不斷跳轉,那么為了方便讀者理解,下面給出一個流程圖,讀者可結合該流程圖以及上面的詳解來進行理解。

注冊流程

注銷

與注冊相對應的是注銷,當訂閱者不再需要事件的時候,我們要注銷這個訂閱者,即調用以下代碼:

EventBus.getDefault().unregister(this);

那么我們來分析注銷流程是怎樣實現的,首先查看 EventBus#unregister

unregister

public synchronized void unregister(Object subscriber) {
    //根據當前的訂閱者來獲取它所訂閱的所有事件
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        //遍歷所有訂閱的事件
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        //從typesBySubscriber中移除該訂閱者
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

上面調用了 EventBus#unsubscribeByEventType ,把訂閱者以及事件作為參數傳遞了進去,那么應該是解除兩者的聯系。

unsubscribeByEventType

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    //根據事件類型從subscriptionsByEventType中獲取相應的 subscriptions 集合
    List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions != null) {
        int size = subscriptions.size();
        //遍歷所有的subscriptions,逐一移除
        for (int i = 0; i < size; i++) {
            Subscription subscription = subscriptions.get(i);
            if (subscription.subscriber == subscriber) {
                subscription.active = false;
                subscriptions.remove(i);
                i--;
                size--;
            }
        }
    }
}

可以看到,上面兩個方法的邏輯是非常清楚的,都是從typesBySubscriber或subscriptionsByEventType移除相應與訂閱者有關的信息,注銷流程相對于注冊流程簡單了很多,其實注冊流程主要邏輯集中于怎樣找到訂閱方法上。

發送事件

接下來,我們分析發送事件的流程,一般地,發送一個事件調用以下代碼:

EventBus.getDefault().post(new MessageEvent("Hello !....."));`

我們來看看 EventBus#post 方法。

post

public void post(Object event) {
    //1、 獲取一個postingState
    PostingThreadState postingState = currentPostingThreadState.get();
    List<Object> eventQueue = postingState.eventQueue;
    //將事件加入隊列中
    eventQueue.add(event);

if (!postingState.isPosting) {
    //判斷當前線程是否是主線程
    postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
    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;
    }
}

}</code></pre>

邏輯非常清晰,首先是獲取一個PostingThreadState,那么PostingThreadState是什么呢?我們來看看它的類結構:

PostingThreadState

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

可以看出,該PostingThreadState主要是封裝了當前線程的信息,以及訂閱者、訂閱事件等。那么怎么得到這個PostingThreadState呢?讓我們回到post()方法,看①號代碼,這里通過currentPostingThreadState.get()來獲取PostingThreadState。那么currentPostingThreadState又是什么呢?

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

原來 currentPostingThreadState是一個ThreadLocal,而ThreadLocal是每個線程獨享的,其數據別的線程是不能訪問的,因此是線程安全的。我們再次回到Post()方法,繼續往下走,是一個while循環,這里不斷地從隊列中取出事件,并且分發出去,調用的是 EventBus#postSingleEvent 方法。

postSingleEvent

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //該eventInheritance上面有提到,默認為true,即EventBus會考慮事件的繼承樹
    //如果事件繼承自父類,那么父類也會作為事件被發送
    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) {
            Log.d(TAG, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

從上面的邏輯來看,對于一個事件,默認地會搜索出它的父類,并且把父類也作為事件之一發送給訂閱者,接著調用了 EventBus#postSingleEventForEventType ,把事件、postingState、事件的類傳遞進去,那么我們來看看這個方法。

postSingleEventForEventType

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        //從subscriptionsByEventType獲取響應的subscriptions
        subscriptions = subscriptionsByEventType.get(eventClass);
    }
    if (subscriptions != null && !subscriptions.isEmpty()) {
        for (Subscription subscription : subscriptions) {
            postingState.event = event;
            postingState.subscription = subscription;
            boolean aborted = false;
            try {
                //發送事件
                postToSubscription(subscription, event, postingState.isMainThread);
                aborted = postingState.canceled;
            } 
            //...
        }
        return true;
    }
    return false;
}

接著,進一步調用了 EventBus#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 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);
    }
}

首先獲取threadMode,即訂閱方法運行的線程,如果是POSTING,那么直接調用invokeSubscriber()方法即可,如果是MAIN,則要判斷當前線程是否是MAIN線程,如果是也是直接調用invokeSubscriber()方法,否則會交給mainThreadPoster來處理,其他情況相類似。這里會用到三個Poster,由于粘性事件也會用到這三個Poster,因此我把它放到下面來專門講述。而 EventBus#invokeSubscriber 的實現也很簡單,主要實現了 利用反射的方式 來調用訂閱方法,這樣就實現了事件發送給訂閱者,訂閱者調用訂閱方法這一過程。如下所示:

invokeSubscriber

void invokeSubscriber(Subscription subscription, Object event) {
    try {
        subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
    } 
    //...
}

到目前為止,事件的發送流程也講解完畢,為了方便理解,整個發送流程也給出相應的流程圖:

發送流程.jpg

粘性事件的發送及接收分析

粘性事件與一般的事件不同,粘性事件是先發送出去,然后讓后面注冊的訂閱者能夠收到該事件。粘性事件的發送是通過 EventBus#postSticky() 方法進行發送的,我們來看它的源碼:

public void postSticky(Object event) {
    synchronized (stickyEvents) {
        stickyEvents.put(event.getClass(), event);
    }
    // Should be posted after it is putted, in case the subscriber wants to remove immediately
    post(event);
}

把該事件放進了 stickyEvents這個map中,接著調用了post()方法,那么流程和上面分析的一樣了,只不過是找不到相應的subscriber來處理這個事件罷了。那么為什么當注冊訂閱者的時候可以馬上接收到匹配的事件呢?還記得上面的EventBus#subscribe方法里面有一段是專門處理粘性事件的代碼嗎?即:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //以上省略...
    //下面是對粘性事件的處理
    if (subscriberMethod.sticky) {
        //從EventBusBuilder可知,eventInheritance默認為true.
        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 {
            //根據eventType,從stickyEvents列表中獲取特定的事件
            Object stickyEvent = stickyEvents.get(eventType);
            //分發事件
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

上面的邏輯很清晰,EventBus并不知道當前的訂閱者對應了哪個粘性事件,因此需要全部遍歷一次,找到匹配的粘性事件后,會調用 EventBus#checkPostStickyEventToSubscription 方法:

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

接著,又回到了postToSubscription方法了,無論對于普通事件或者粘性事件,都會根據threadMode來選擇對應的線程來執行訂閱方法,而切換線程的關鍵所在就是mainThreadPoster、backgroundPoster和asyncPoster這三個Poster。

HandlerPoster

我們首先看mainThreadPoster,它的類型是HandlerPoster繼承自Handler:

final class HandlerPoster extends Handler {

//PendingPostQueue隊列,待發送的post隊列
private final PendingPostQueue queue;
//規定最大的運行時間,因為運行在主線程,不能阻塞主線程
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
//省略...

}</code></pre>

可以看到,該handler內部有一個PendingPostQueue,這是一個隊列,保存了PendingPost,即待發送的post,該PendingPost封裝了event和subscription,方便在線程中進行信息的交互。在postToSubscription方法中,當前線程如果不是主線程的時候,會調用 HandlerPoster#enqueue 方法:

void enqueue(Subscription subscription, Object event) {
    //將subscription和event打包成一個PendingPost
    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    synchronized (this) {
        //入隊列
        queue.enqueue(pendingPost);
        if (!handlerActive) {
            handlerActive = true;
            //發送消息,在主線程運行
            if (!sendMessage(obtainMessage())) {
                throw new EventBusException("Could not send handler message");
            }
        }
    }
}

首先會從PendingPostPool中獲取一個可用的PendingPost,接著把該PendingPost放進PendingPostQueue,發送消息,那么由于該HandlerPoster在初始化的時候獲取了UI線程的Looper,所以它的handleMessage()方法運行在UI線程:

@Override
public void handleMessage(Message msg) {
    boolean rescheduled = false;
    try {
        long started = SystemClock.uptimeMillis();
        //不斷從隊列中取出pendingPost
        while (true) {
            //省略...
            eventBus.invokeSubscriber(pendingPost);        
            //..
        }
    } finally {
        handlerActive = rescheduled;
    }
}

里面調用到了 EventBus#invokeSubscriber 方法,在這個方法里面,將PendingPost解包,進行正常的事件分發,這上面都說過了,就不展開說了。

BackgroundPoster

BackgroundPoster繼承自Runnable,與HandlerPoster相似的,它內部都有PendingPostQueue這個隊列,當調用到它的enqueue的時候,會將subscription和event打包成PendingPost:

public void enqueue(Subscription subscription, Object event) {
    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    synchronized (this) {
        queue.enqueue(pendingPost);
        //如果后臺線程還未運行,則先運行
        if (!executorRunning) {
            executorRunning = true;
            //會調用run()方法
            eventBus.getExecutorService().execute(this);
        }
    }
}

該方法通過Executor來運行run()方法,run()方法內部也是調用到了 EventBus#invokeSubscriber 方法。

AsyncPoster

與BackgroundPoster類似,它也是一個Runnable,實現原理與BackgroundPoster大致相同,但有一個不同之處,就是它內部不用判斷之前是否已經有一條線程已經在運行了,它每次post事件都會使用新的一條線程。

再談觀察者模式

整個EventBus是基于觀察者模式而構建的,而上面的調用觀察者的方法則是觀察者模式的核心所在。

觀察者模式:定義了對象之間的一對多依賴,當一個對象改變狀態時,它的所有依賴者都會收到通知并自動更新。

從整個EventBus可以看出,事件是被觀察者,訂閱者類是觀察者,當事件出現或者發送變更的時候,會通過EventBus通知觀察者,使得觀察者的訂閱方法能夠被自動調用。當然了,這與一般的觀察者模式有所不同。回想我們所用過的觀察者模式,我們會讓事件實現一個接口或者直接繼承自Java內置的Observerable類,同時在事件內部還持有一個列表,保存所有已注冊的觀察者,而事件類還有一個方法用于通知觀察者的。那么從 單一職責原則 的角度來說,這個事件類所做的事情太多啦!既要記住有哪些觀察者,又要等到時機成熟的時候通知觀察者,又或者有別的自身的方法。這樣的話,一兩件事件類還好,但如果對于每一個事件類,每一個新的不同的需求,都要實現相同的操作的話,這是非常繁瑣而且低效率的。因此, EventBus就充當了中介的角色 ,把事件的很多責任抽離出來,使得事件自身不需要實現任何東西,別的都交給EventBus來操作就可以了。

好了,本文到此為止已經對EventBus進行了一次詳細的講解,由于本文很長,建議讀者可以選擇難懂的部分對照源碼反復思考以便能深刻理解。最后,為堅持讀完本文的你點贊,謝謝你們的閱讀!

 

 

來自:http://www.jianshu.com/p/bda4ed3017ba

 

 本文由用戶 thau6663 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!