EventBus源碼分析

前面對(duì)EventBus 的簡(jiǎn)單實(shí)用寫了一篇,相信大家都會(huì)使用,如果使用的還不熟,或者不夠6,可以花2分鐘瞄一眼:http://www.lxweimin.com/p/321108571fd0

源碼分析準(zhǔn)備工作

原因:好多同事同學(xué)最近出去面試都問(wèn),其實(shí)我很早前看過(guò)了,現(xiàn)在記不住了,而且自己使用的東西最好知道所以然
版本:EventBus 3.0

源碼結(jié)構(gòu)圖

EventBus.png

獲取實(shí)例并注冊(cè)

EventBus.getDefault().register(this);

1.getDefault()的源碼是怎樣的,代碼如下,很明顯是單例模式!雙重鎖校驗(yàn),并且實(shí)例使用了關(guān)鍵字volatile 修飾,保證線程安全,簡(jiǎn)單說(shuō)一下volatile,只作用于變量,讓變量在各個(gè)線程可見(jiàn)的。不能保證原子性,比如i++ ,分3步,從內(nèi)存讀出i ,然后i++ ,然后在寫到內(nèi)存,這也是內(nèi)存模型的知識(shí),也就是 可能在第一步還沒(méi)搞完,就讀回去了,這個(gè)一般區(qū)別synchronized ,synchronized 有可能會(huì)造成線程阻塞,不多說(shuō)了,回到本質(zhì)。

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

2.我們繼續(xù)看下Eventbus的構(gòu)造方法:

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

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

構(gòu)造使用的public 修飾?不怕我創(chuàng)建對(duì)象嗎,我在看源碼時(shí)就比較好奇,發(fā)現(xiàn)他的注釋:創(chuàng)建事件總線實(shí)例都在他的范圍內(nèi),推薦我們用中央bus考慮使用單例!也就是每一個(gè)EventBus都是獨(dú)立地、處理它們自己的事件,因此可以存在多個(gè)EventBus而通過(guò)getDefault()方法獲取的實(shí)例,則是它已經(jīng)幫我們構(gòu)建好的EventBus,是單例,無(wú)論在什么時(shí)候通過(guò)這個(gè)方法獲取的實(shí)例都是同一個(gè)實(shí)例。

進(jìn)行了一堆成員變量的初始化操作,重點(diǎn)看下這幾個(gè)關(guān)鍵的成員變量,看下等會(huì)他們干什么的

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,事件發(fā)送之后,在這里尋找訂閱者
而Subscription又是一個(gè)CopyOnWriteArrayList,這是一個(gè)線程安全的容器 ,Subscription是一個(gè)封裝類,封裝了訂閱者、訂閱方法這兩個(gè)類。它的構(gòu)造如下:

   Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
        this.subscriber = subscriber;
        this.subscriberMethod = subscriberMethod;
        active = true;
    }
typesBySubscriber

以訂閱者類為key,以event事件類為value,在進(jìn)行register或unregister操作的時(shí)候,會(huì)操作這個(gè)hashmap

stickyEvents

保存的是粘性事件
接下來(lái)實(shí)例化了三個(gè)Poster,分別是mainThreadPoster、backgroundPoster、asyncPoster等,這三個(gè)Poster是用來(lái)處理粘性事件的,然后使用建造者模式對(duì)

EventBusBuilder,它的一系列方法用于配置EventBus的屬性,使用getDefault()方法獲取的實(shí)例,會(huì)有著默認(rèn)的配置,上面說(shuō)過(guò),EventBus的構(gòu)造方法是公有的,所以我們可以通過(guò)給EventBusBuilder設(shè)置不同的屬性,進(jìn)而獲取有著不同功能的EventBus。

我們通過(guò)建造者模式來(lái)手動(dòng)創(chuàng)建一個(gè)EventBus,而不是使用getDefault()方法:

EventBus eventBus = EventBus.builder()
        .eventInheritance(false) //默認(rèn)地,EventBus會(huì)考慮事件的超類,即事件如果繼承自超類,那么該超類也會(huì)作為事件發(fā)送給訂閱者如果設(shè)置為false,則EventBus只會(huì)考慮事件類本身
        .sendNoSubscriberEvent(true)
        .skipMethodVerificationFor(MainActivity.class)
        .build();

注冊(cè)

EventBus的創(chuàng)建,接下來(lái),我們繼續(xù)講它的注冊(cè)過(guò)程。要想使一個(gè)類成為訂閱者,那么這個(gè)類必須有一個(gè)訂閱方法,以@Subscribe注解標(biāo)記的方法,接著調(diào)用register()方法來(lái)進(jìn)行注冊(cè)

1.注冊(cè): 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()處理,返回結(jié)果保存在List<SubscriberMethod>中,由此可推測(cè)通過(guò)上面的方法把訂閱方法找出來(lái)了,并保存在集合中,那么我們直接看這個(gè)方

private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();
....

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

這個(gè)里面就是傳入注冊(cè)的類,首先是從METHOD_CACHE這個(gè)ConcurrentHashMap 里面獲取,而這個(gè)map 存放的是key :類。value 就是所有的訂閱方法放在list中,如果獲取到就返回這個(gè)訂閱方法的list 沒(méi)有緩存,繼續(xù)往下走,通過(guò)EventBus 的構(gòu)造可以知道,這個(gè)標(biāo)志位。ignoreGennerratedIndex 默認(rèn)false 就是在建造者初始化時(shí)候,一般會(huì)調(diào)用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();
        }
        return getMethodsAndRelease(findState);
    }

上面用到了FindState這個(gè)內(nèi)部類來(lái)保存訂閱者類的信息,我們看看它的內(nèi)部結(jié)構(gòu)

 static class FindState {
        final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
        final Map<Class, Object> anyMethodByEventType = new HashMap<>();
        final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

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

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

       ....

該內(nèi)部類保存了訂閱者及其訂閱方法的信息,用Map一一對(duì)應(yīng)進(jìn)行保存,接著利用initForSubscriber進(jìn)行初始化,這里subscriberInfo初始化為null ,所以,findUsingInfo方法中會(huì)調(diào)用findUsingReflectionInSingleClass(findState)

在這個(gè)方法中利用反射的方式,對(duì)訂閱者類進(jìn)行掃描,找出訂閱方法,并用上面的Map進(jìn)行保存,我們來(lái)看這個(gè)方法 逐一判斷訂閱者類是否存在訂閱方法,如果符合要求,調(diào)用findState.checkAdd(method, eventType)返回true的時(shí)候,才會(huì)把方法保存在findState的subscriberMethods內(nèi)。而SubscriberMethod則是用于保存訂閱方法的一個(gè)類
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()));
                        }
                    }
                } 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");
            }
        }
    }

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

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

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

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

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

checkAdd和checkAddWithMethodSignature方法的源碼,那么這兩個(gè)方法到底有什么作用呢?從這兩個(gè)方法的邏輯來(lái)看,第一層判斷根據(jù)eventType來(lái)判斷是否有多個(gè)方法訂閱該事件,而第二層判斷根據(jù)完整的方法簽名(包括方法名字以及參數(shù)名字)來(lái)判斷。
第一種情況:比如一個(gè)類有多個(gè)訂閱方法,方法名不同,但它們的參數(shù)類型都是相同的(雖然一般不這樣寫,但不排除這樣的可能),那么遍歷這些方法的時(shí)候,會(huì)多次調(diào)用到checkAdd方法,由于existing不為null,那么會(huì)進(jìn)而調(diào)用checkAddWithMethodSignature方法,但是由于每個(gè)方法的名字都不同,因此methodClassOld會(huì)一直為null,因此都會(huì)返回true。也就是說(shuō),允許一個(gè)類有多個(gè)參數(shù)相同的訂閱方法。

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

讓我們回到findUsingReflectionInSingleClass方法,當(dāng)遍歷完當(dāng)前類的所有方法后,會(huì)回到findUsingInfo方法,接著會(huì)執(zhí)行最后一行代碼,即return getMethodsAndRelease(findState);那么我們繼續(xù)

SubscriberMethodFinder#getMethodsAndRelease方法

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
    //從findState獲取subscriberMethods,放進(jìn)新的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;
}

通過(guò)該方法,把subscriberMethods不斷逐層返回,直到返回EventBus#register()方法,最后開(kāi)始遍歷每一個(gè)訂閱方法,并調(diào)用subscribe(subscriber, subscriberMethod)方法,那么,我們繼續(xù)來(lái)看EventBus#subscribe方法

subscribe

方法內(nèi),主要是實(shí)現(xiàn)訂閱方法與事件直接的關(guān)聯(lián),即注冊(cè),即放進(jìn)我們上面提到關(guān)鍵的幾個(gè)Map中:subscriptionsByEventType、typesBySubscriber、stickyEvents

// Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

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

        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        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);
            }
        }
    }

訂閱方法中,將訂閱類和訂閱方法,封裝成一個(gè)Subscription 對(duì)象,再據(jù)事件類型獲取特定的 Subscription,如果為null,說(shuō)明該subscriber尚未注冊(cè)該事件 如果不為null,并且包含了這個(gè)subscription 那么說(shuō)明該subscriber已經(jīng)注冊(cè)了該事件,拋出異常
根據(jù)優(yōu)先級(jí)來(lái)設(shè)置放進(jìn)subscriptions的位置,優(yōu)先級(jí)高的會(huì)先被通知
根據(jù)subscriber(訂閱者)來(lái)獲取它的所有訂閱事件

注冊(cè)流程基本分析完畢,而關(guān)于最后的粘性事件的處理,這里暫時(shí)不說(shuō),下面會(huì)詳細(xì)進(jìn)行講述。可以看出,整個(gè)注冊(cè)流程非常地長(zhǎng),方法的調(diào)用棧很深,在各個(gè)方法中不斷跳轉(zhuǎn),那么為了方便讀者理解,下面給出一個(gè)流程圖,讀者可結(jié)合該流程圖以及上面的詳解來(lái)進(jìn)行理解。

注銷

與注冊(cè)相對(duì)應(yīng)的是注銷,當(dāng)訂閱者不再需要事件的時(shí)候,我們要注銷這個(gè)訂閱者,即調(diào)用以下代碼:

EventBus.getDefault().unregister(this);

那么我們來(lái)分析注銷流程是怎樣實(shí)現(xiàn)的,首先查看EventBus#unregister:

unregister

public synchronized void unregister(Object subscriber) {
    //根據(jù)當(dāng)前的訂閱者來(lái)獲取它所訂閱的所有事件
    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());
    }
}

上面調(diào)用了EventBus#unsubscribeByEventType,把訂閱者以及事件作為參數(shù)傳遞了進(jìn)去,那么應(yīng)該是解除兩者的聯(lián)系。

unsubscribeByEventType

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    //根據(jù)事件類型從subscriptionsByEventType中獲取相應(yīng)的 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--;
            }
        }
    }
}

可以看到,上面兩個(gè)方法的邏輯是非常清楚的,都是從typesBySubscriber或subscriptionsByEventType移除相應(yīng)與訂閱者有關(guān)的信息,注銷流程相對(duì)于注冊(cè)流程簡(jiǎn)單了很多,其實(shí)注冊(cè)流程主要邏輯集中于怎樣找到訂閱方法上

發(fā)送事件

接下來(lái),我們分析發(fā)送事件的流程,一般地,發(fā)送一個(gè)事件調(diào)用以下代碼:

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

我們來(lái)看看EventBus#post方法。

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

    if (!postingState.isPosting) {
        //判斷當(dāng)前線程是否是主線程
        postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
        postingState.isPosting = true;
        if (postingState.canceled) {
            throw new EventBusException("Internal error. Abort state was not reset");
        }
        try {
            //只要隊(duì)列不為空,就不斷從隊(duì)列中獲取事件進(jìn)行分發(fā)
            while (!eventQueue.isEmpty()) {
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

首先是獲取一個(gè)PostingThreadState,那么PostingThreadState是什么呢?我們來(lái)看看它的類結(jié)構(gòu):

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

可以看出,該P(yáng)ostingThreadState主要是封裝了當(dāng)前線程的信息,以及訂閱者、訂閱事件等。那么怎么得到這個(gè)PostingThreadState呢?讓我們回到post()方法再通過(guò)currentPostingThreadState.get()來(lái)獲取PostingThreadState。那么currentPostingThreadState又是什么呢?

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

來(lái) currentPostingThreadState是一個(gè)ThreadLocal,而ThreadLocal是每個(gè)線程獨(dú)享的,其數(shù)據(jù)別的線程是不能訪問(wèn)的,因此是線程安全的。我們?cè)俅位氐絇ost()方法,繼續(xù)往下走,是一個(gè)while循環(huán),這里不斷地從隊(duì)列中取出事件,并且分發(fā)出去,調(diào)用的是EventBus#postSingleEvent方法

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //該eventInheritance上面有提到,默認(rèn)為true,即EventBus會(huì)考慮事件的繼承樹(shù)
    //如果事件繼承自父類,那么父類也會(huì)作為事件被發(fā)送
    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);
    }
    //如果沒(méi)找到訂閱該事件的訂閱者
    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));
        }
    }
}

從上面的邏輯來(lái)看,對(duì)于一個(gè)事件,默認(rèn)地會(huì)搜索出它的父類,并且把父類也作為事件之一發(fā)送給訂閱者,接著調(diào)用了EventBus#postSingleEventForEventType,把事件、postingState、事件的類傳遞進(jìn)去,那么我們來(lái)看看這個(gè)方法
postSingleEventForEventType

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

接著,進(jìn)一步調(diào)用了EventBus#postToSubscription,可以發(fā)現(xiàn),這里把訂閱列表作為參數(shù)傳遞了進(jìn)去,顯然,訂閱列表內(nèi)部保存了訂閱者以及訂閱方法,那么可以猜測(cè),這里應(yīng)該是通過(guò)反射的方式來(lái)調(diào)用訂閱方法。具體怎樣的話,我們看源碼。

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,即訂閱方法運(yùn)行的線程,如果是POSTING,那么直接調(diào)用invokeSubscriber()方法即可,如果是MAIN,則要判斷當(dāng)前線程是否是MAIN線程,如果是也是直接調(diào)用invokeSubscriber()方法,否則會(huì)交給mainThreadPoster來(lái)處理,其他情況相類似。這里會(huì)用到三個(gè)Poster,由于粘性事件也會(huì)用到這三個(gè)Poster,因此我把它放到下面來(lái)專門講述。而EventBus#invokeSubscriber的實(shí)現(xiàn)也很簡(jiǎn)單,主要實(shí)現(xiàn)了利用反射的方式來(lái)調(diào)用訂閱方法,這樣就實(shí)現(xiàn)了事件發(fā)送給訂閱者,訂閱者調(diào)用訂閱方法這一過(guò)程。如下所示:

invokeSubscriber

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

粘性事件的發(fā)送及接收分析

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

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

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

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //以上省略...
    //下面是對(duì)粘性事件的處理
    if (subscriberMethod.sticky) {
        //從EventBusBuilder可知,eventInheritance默認(rèn)為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>).
            //從列表中獲取所有粘性事件,由于粘性事件的性質(zhì),我們不知道它對(duì)應(yīng)哪些訂閱者,
            //因此,要把所有粘性事件取出來(lái),逐一遍歷
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                //如果訂閱者訂閱的事件類型與當(dāng)前的粘性事件類型相同,那么把該事件分發(fā)給這個(gè)訂閱者
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            //根據(jù)eventType,從stickyEvents列表中獲取特定的事件
            Object stickyEvent = stickyEvents.get(eventType);
            //分發(fā)事件
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

上面的邏輯很清晰,EventBus并不知道當(dāng)前的訂閱者對(duì)應(yīng)了哪個(gè)粘性事件,因此需要全部遍歷一次,找到匹配的粘性事件后,會(huì)調(diào)用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方法了,無(wú)論對(duì)于普通事件或者粘性事件,都會(huì)根據(jù)threadMode來(lái)選擇對(duì)應(yīng)的線程來(lái)執(zhí)行訂閱方法,而切換線程的關(guān)鍵所在就是mainThreadPoster、backgroundPoster和asyncPoster這三個(gè)Poster。

HandlerPoster

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

final class HandlerPoster extends Handler {

    //PendingPostQueue隊(duì)列,待發(fā)送的post隊(duì)列
    private final PendingPostQueue queue;
    //規(guī)定最大的運(yùn)行時(shí)間,因?yàn)檫\(yùn)行在主線程,不能阻塞主線程
    private final int maxMillisInsideHandleMessage;
    private final EventBus eventBus;
    private boolean handlerActive;
    //省略...
}

可以看到,該handler內(nèi)部有一個(gè)PendingPostQueue,這是一個(gè)隊(duì)列,保存了PendingPost,即待發(fā)送的post,該P(yáng)endingPost封裝了event和subscription,方便在線程中進(jìn)行信息的交互。在postToSubscription方法中,當(dāng)前線程如果不是主線程的時(shí)候,會(huì)調(diào)用HandlerPoster#enqueue方法:

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

首先會(huì)從PendingPostPool中獲取一個(gè)可用的PendingPost,接著把該P(yáng)endingPost放進(jìn)PendingPostQueue,發(fā)送消息,那么由于該HandlerPoster在初始化的時(shí)候獲取了UI線程的Looper,所以它的handleMessage()方法運(yùn)行在UI線程:

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

里面調(diào)用到了EventBus#invokeSubscriber方法,在這個(gè)方法里面,將PendingPost解包,進(jìn)行正常的事件分發(fā),這上面都說(shuō)過(guò)了,就不展開(kāi)說(shuō)了。

BackgroundPoster

BackgroundPoster繼承自Runnable,與HandlerPoster相似的,它內(nèi)部都有PendingPostQueue這個(gè)隊(duì)列,當(dāng)調(diào)用到它的enqueue的時(shí)候,會(huì)將subscription和event打包成PendingPost:

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

該方法通過(guò)Executor來(lái)運(yùn)行run()方法,run()方法內(nèi)部也是調(diào)用到了EventBus#invokeSubscriber方法。

AsyncPoster

與BackgroundPoster類似,它也是一個(gè)Runnable,實(shí)現(xiàn)原理與BackgroundPoster大致相同,但有一個(gè)不同之處,就是它內(nèi)部不用判斷之前是否已經(jīng)有一條線程已經(jīng)在運(yùn)行了,它每次post事件都會(huì)使用新的一條線程

其他

整個(gè)EventBus是基于觀察者模式而構(gòu)建的,而上面的調(diào)用觀察者的方法則是觀察者模式的核心所在。

觀察者模式:定義了對(duì)象之間的一對(duì)多依賴,當(dāng)一個(gè)對(duì)象改變狀態(tài)時(shí),它的所有依賴者都會(huì)收到通知并自動(dòng)更新。
從整個(gè)EventBus可以看出,事件是被觀察者,訂閱者類是觀察者,當(dāng)事件出現(xiàn)或者發(fā)送變更的時(shí)候,會(huì)通過(guò)EventBus通知觀察者,使得觀察者的訂閱方法能夠被自動(dòng)調(diào)用。當(dāng)然了,這與一般的觀察者模式有所不同。回想我們所用過(guò)的觀察者模式,我們會(huì)讓事件實(shí)現(xiàn)一個(gè)接口或者直接繼承自Java內(nèi)置的Observerable類,同時(shí)在事件內(nèi)部還持有一個(gè)列表,保存所有已注冊(cè)的觀察者,而事件類還有一個(gè)方法用于通知觀察者的。那么從單一職責(zé)原則的角度來(lái)說(shuō),這個(gè)事件類所做的事情太多啦!既要記住有哪些觀察者,又要等到時(shí)機(jī)成熟的時(shí)候通知觀察者,又或者有別的自身的方法。這樣的話,一兩件事件類還好,但如果對(duì)于每一個(gè)事件類,每一個(gè)新的不同的需求,都要實(shí)現(xiàn)相同的操作的話,這是非常繁瑣而且低效率的。因此,EventBus就充當(dāng)了中介的角色,把事件的很多責(zé)任抽離出來(lái),使得事件自身不需要實(shí)現(xiàn)任何東西,別的都交給EventBus來(lái)操作就可以

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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

  • EventBus源碼分析(一) EventBus官方介紹為一個(gè)為Android系統(tǒng)優(yōu)化的事件訂閱總線,它不僅可以很...
    蕉下孤客閱讀 4,047評(píng)論 4 42
  • EventBus源碼分析 Android開(kāi)發(fā)中我們最常用到的可以說(shuō)就是EventBus了,今天我們來(lái)深入研究一下E...
    BlackFlag閱讀 515評(píng)論 3 4
  • 前言 EventBus是Android端的一個(gè)訂閱/發(fā)布的消息總線,用于Activity、Fragment、Thr...
    小川君閱讀 303評(píng)論 0 0
  • 停停走走又幾天,斷斷續(xù)續(xù)這一年。時(shí)間還是如此之快,轉(zhuǎn)眼間又到了17年的末尾了。趁著這些天還能靜下心來(lái)看看代碼,趕緊...
    nick_young閱讀 1,298評(píng)論 0 3
  • ------二零一七年,夏。 深圳,延續(xù)著暴雨淹城的架勢(shì),一輪接一輪的臺(tái)風(fēng)席卷,讓那座充滿活力的城市街道失去了熱辣...
    兔子眉毛閱讀 317評(píng)論 0 0