EventBus源碼詳解缓升,看這一篇就夠了

之前寫過一篇關(guān)于EventBus的文章,大家的反饋還不錯(EventBus3.0使用詳解)邮辽,如果你還沒有使用過EventBus唠雕,可以去那篇文章看看扣蜻。當(dāng)時剛接觸EventBus,對它的理解也僅僅是停留在表面,寫那篇文章也是記錄下EventBus的一個簡單的使用的過程及塘,而如今隨著EventBus在項目中的多次運用,個人感覺锐极,會用一個框架跟知道它的原理這是兩碼事笙僚,所以下定決心寫這篇文章來幫助自己更好的理解EventBus。

在進入主題之前灵再,我們先保持著這樣幾個疑問肋层,EventBus的使用三要素里,我們?yōu)槭裁匆ザx事件方法翎迁,并且用到了@subscribe()注解栋猖? EventBus.getDefault().register(Object)這行代碼到底干了什么?發(fā)送事件的時候又做了哪些操作汪榔?為什么要在onDestory()做解除綁定的操作...等等

(一) 注冊: EventBus.getDefault().register(obj)

首先調(diào)用EventBus的靜態(tài)getDefault()方法返回一個EventBus對象蒲拉,采用單例實現(xiàn)。

//  靜態(tài)的單例
static volatile EventBus defaultInstance;

// 默認(rèn)的EventBusBuilder對象
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

//  使用了單例的雙重鎖機制
public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

 //  調(diào)用帶參數(shù)的構(gòu)造方法
 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;
 }

在EventBus(builder)構(gòu)造方法里初始化了一些配置信息痴腌。

之后調(diào)用了EventBus的register(obj)方法雌团,這個方法接收的參數(shù)類型是Object。這里我們分步驟1和步驟2去看看做了哪些操作士聪。

public void register(Object subscriber) {
        //  通過反射拿到傳入的obj的Class對象锦援,如果是在MainActivity里做的注冊操作仓技,
        //  那subscriber就是MainActivity對象
        Class<?> subscriberClass = subscriber.getClass();
        // 步驟1 
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        //  步驟2
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

步驟1

List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

首先subscriberMethodFinder對象是在EventBus帶參數(shù)的構(gòu)造函數(shù)里進行初始化的腕侄,從這個findSubscriberMethods()方法名就可以看出來,步驟1的是去獲取當(dāng)前注冊的對象里所有的被@Subscribe注解的方法集合慈省,那這個List集合的對象SubscriberMethod又是什么東東呢区岗? 我們?nèi)タ匆幌?/p>

public class SubscriberMethod {
    final Method method;
    final ThreadMode threadMode;
    final Class<?> eventType;
    final int priority;
    final boolean sticky;
    /** Used for efficient comparison */
    String methodString;

    public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
        this.method = method;
        this.threadMode = threadMode;
        this.eventType = eventType;
        this.priority = priority;
        this.sticky = sticky;
    }
}
...

看完這個類里定義的信息略板,大概明白了。SubscriberMethod 定義了Method方法名慈缔,ThreadMode 線程模型蚯根,eventType 事件的class對象,priority是指接收事件的優(yōu)先級胀糜,sticky是指是否是粘性事件颅拦,SubscriberMethod 對這些信息做了一個封裝。這些信息在我們處理事件的時候都會用到:

@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void XXX(MessageEvent messageEvent) {
    ...
}

好的教藻,知道了SubscriberMethod 是什么東東后距帅,我們直接進入findSubscriberMethods(subscriberClass)方法。

 List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
         //  METHOD_CACHE是事先定義了一個緩存Map,以當(dāng)前的注冊對象的Class對象為key,注冊的對象里所有的被@Subscribe注解的方法集合為value
         List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);

        // 第一次進來的時候括堤,緩存里面沒有集合碌秸,subscriberMethods 為null
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        // ignoreGeneratedIndex是在SubscriberMethodFinder()的構(gòu)造函數(shù)初始化的绍移,默認(rèn)值是 false
        if (ignoreGeneratedIndex) {
            //  通過反射去獲取 
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
           //  通過apt插件生成的代碼。使用subscriber Index生成的SubscriberInfo來獲取訂閱者的事件處理函數(shù)讥电,
            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;
        }
    }

首先是從緩存中獲取蹂窖,如果緩存中存在直接返回,這里使用緩存有一個 好處恩敌,比如在MainActivity進行了注冊操作瞬测,多次啟動MainActivity,就會直接去緩存中拿數(shù)據(jù)纠炮。如果緩存里沒有數(shù)據(jù)月趟,就會根據(jù)ignoreGeneratedIndex 這個boolean值去調(diào)用不同的方法,ignoreGeneratedIndex 默認(rèn)為false恢口。如果此時孝宗,獲取到的方法集合還是空的,程序就會拋出異常耕肩,提醒用戶被注冊的對象以及他的父類沒有被@Subscribe注解的public方法(這里插一句因妇,很多時候,如果打正式包的時候EventBus沒有做混淆處理猿诸,就會拋出該異常沙峻,因為方法名被混淆處理了,EventBus會找不到)两芳,把獲取到的方法集合存入到緩存中去摔寨,并且把方法集合return出去。

大致的流程就是這樣怖辆,findSubscriberMethods()負(fù)責(zé)獲取注冊對象的方法集合是复,優(yōu)先從緩存中獲取,緩存中不存在竖螃,則根據(jù)ignoreGeneratedIndex是true或false,如果ignoreGeneratedIndex為true,則調(diào)用findUsingReflection()淑廊,如果為false,則調(diào)用findUsingInfo()方法去獲取方法集合

findUsingInfo():

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        // 這里采用了享元設(shè)計模式
        FindState findState = prepareFindState();
        // 初始化FindState里的參數(shù)
        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對象采用了享元模式
private FindState prepareFindState() {
        synchronized (FIND_STATE_POOL) {
            for (int i = 0; i < POOL_SIZE; i++) {
                FindState state = FIND_STATE_POOL[i];
                if (state != null) {
                    FIND_STATE_POOL[i] = null;
                    return state;
                }
            }
        }
        return new FindState();
    }

// FindState類定義的信息
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;
        }
....
....
}

獲取FindState采用了享元模式特咆,這里不多說季惩。之后調(diào)用了 findState.initForSubscriber(subscriberClass)方法,只是為了給FindState對象里的一些信息進行賦值操作腻格。再然后是一個 while循環(huán)画拾,循環(huán)里首先調(diào)用getSubscriberInfo(findState)方法,點進去看一下菜职,發(fā)現(xiàn)該方法返回null青抛。這里留一個小疑問,getSubscriberInfo()方法什么時候不為null酬核?蜜另? 答案在最后一節(jié)的高級用法里

private SubscriberInfo getSubscriberInfo(FindState findState) {
        //  findState.subscriberInfo在初始化的時候置為null适室,所以該if 分支不會執(zhí)行

        if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
            SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
            if (findState.clazz == superclassInfo.getSubscriberClass()) {
                return superclassInfo;
            }
        }
       //  subscriberInfoIndexes初始化的時候也是null,并沒有賦值
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }

所以findUsingInfo()的while循環(huán)里直接走了else分支:findUsingReflectionInSingleClass(findState)举瑰。

也就是說findUsingInfo()方法的主要邏輯是由findUsingReflectionInSingleClass()方法去完成的(默認(rèn)情況捣辆,不考慮使用apt)

這里有個細(xì)節(jié)要看一下:

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

這個while循環(huán)什么時候結(jié)束呢?這是我們第一次看EventBus源碼看到這里比較疑惑的地方此迅,答案就在這個 findState.moveToSuperclass()里面汽畴。

void moveToSuperclass() {
            if (skipSuperClasses) {
                clazz = null;
            } else {
                clazz = clazz.getSuperclass();
                String clazzName = clazz.getName();
                /** Skip system classes, this just degrades performance. */
                if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
                    clazz = null;
                }
            }
 }

我們可以看到去把clazz賦值為它的超類,直到?jīng)]有父類為止邮屁,才返回clazz=null,循環(huán)也才終止菠齿。也就是說 這個while循環(huán)保證了佑吝,獲取注解的方法不僅會從當(dāng)前注冊對象里去找,也會去從他的父類查找绳匀。

好了芋忿,繼續(xù)分析findUsingReflectionInSingleClass(findState)方法。

private void findUsingReflectionInSingleClass(FindState findState) {
        Method[] methods;
        try {
           // 查找注冊對象的所有方法疾棵,注意是所有
            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;
        }
        //  執(zhí)行遍歷操作
        for (Method method : methods) {
            //  獲取該方法的修飾符,即public戈钢、private等
            int modifiers = method.getModifiers();

            // 修飾符是public才會走該分支
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                // 這里是回去該方法的參數(shù)類型,String是尔,in
                Class<?>[] parameterTypes = method.getParameterTypes();
  
               //  只有一個參數(shù)會走該分支
                if (parameterTypes.length == 1) {

                    //  如果該方法被@subscribe注解會走該分支
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                    //  獲取傳入的對象的Class
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            // 獲取注解上指定的 線程模型
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                           // 往集合中添加數(shù)據(jù)
                            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");
            }
        }
    }

findUsingReflectionInSingleClass()方法首先通過反射去拿到當(dāng)前注冊對象的所有的方法殉了,然后去進行遍歷,并進行第一次過濾拟枚,只針對修飾符是Public的方法薪铜,之后進行了第二次過濾,判斷了方法的參數(shù)的個數(shù)是不是只有一個恩溅,如果滿足隔箍,才去進一步的獲取被@subscribe注解的方法。

然后調(diào)用
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,subscribeAnnotation.priority(), subscribeAnnotation.sticky()))這行代碼脚乡,new了一個SubscriberMethod()對象蜒滩,傳入?yún)?shù),并添加到 findState.subscriberMethods的集合中去.

 static class FindState {
       final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
 }

之后奶稠,findUsingInfo()的getMethodsAndRelease(findState)方法回去獲取剛剛設(shè)置的findState的subscriberMethods集合俯艰,并把它return出去。代碼如下:

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        //  對subscriberMethods進行了賦值锌订,return出去
        List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
       //  進行了回收
        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;
    }

步驟1總結(jié):至此蟆炊,以上就是EventBus獲取一個注冊對象的所有的被@subscribe注解的方法的集合的一個過程。該過程的主要方法流程為:

(1) subscriberMethodFinder.findSubscriberMethods()
(2) findUsingInfo()
(3) findUsingReflectionInSingleClass()

步驟2

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

通過步驟1瀑志,我們已經(jīng)拿到了注冊對象的所有的被@subscribe注解的方法的集合的∩辏現(xiàn)在我們看看subscribe()都做了哪些 操作污秆。

我們不妨想想,如果我們要去做subscribe()時昧甘,我們要考慮哪些問題良拼,第一個問題是,要判斷一下這些方法是不是已經(jīng)注冊過該事件了要不要考慮方法名是不是相同的問題充边。第二個問題是一個注冊對象中有多個方法注冊了該事件庸推,我們該怎么保存這些方法,比如說事件類型是String,一個Activity里有兩個方法注冊了該事件浇冰,分別是onEvent1和onEvent2贬媒,那我是不是應(yīng)該用一個Map集合,以事件類型為key肘习,把onEvent1和onEvent2放到一個List集合中际乘,把該List集合作為value。

subscribe()方法:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        // 拿到事件event類型漂佩,比如是String或者自定義的對象
        Class<?> eventType = subscriberMethod.eventType;

        //  Subscription將注冊對象和subscriberMethod 做為參數(shù)傳入

        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
  
       // subscriptionsByEventType是一個Map集合脖含,key是事件類型,驗證了我上面的猜想
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);

       // 如果subscriptions是null,則new出一個CopyOnWriteArrayList投蝉,并且往Map集合中添加
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
      
      //  這里做了if語句判斷养葵,判斷一下List集合中是否存在,存在就拋異常
      //  如果不存在瘩缆?怎么沒有add操作关拒? 保持疑問

            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

以上的操作驗證了我之前的猜想,通過if (subscriptions.contains(newSubscription)) 這個if語句判斷 是否發(fā)生了重復(fù)注冊庸娱,注意這里重復(fù)注冊的含義是 事件類型一致夏醉,以及方法名也一致。

接下來我們看看如果一個注冊對象重復(fù)注冊了事件Event(方法名不能一致)涌韩,優(yōu)先級priority是如何設(shè)置的

  int size = subscriptions.size();
   for (int i = 0; i <= size; i++) {

      //  這里判斷subscriberMethod的優(yōu)先級是否是大于集合中的subscriberMethod的優(yōu)先級畔柔,如果是,把newSubscription插進去
     //  這也表明了subscription中priority大的在前臣樱,這樣在事件分發(fā)時就會先獲取靶擦。
             if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

if語句的條件subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) ,保證了subscription中priority大的在前雇毫。同時i == size 這個條件也保證了priority小的也會添加到subscriptions集合中去

緊接著我們看看EventBus是如何處理粘性事件的

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

注意以上代碼有四行比較重要的注釋信息玄捕。大致的意思是必須考慮eventType所有子類的現(xiàn)有粘性事件,在迭代的過程中棚放,所有的event可能會因為大量的sticky events變得低效枚粘,為了使得查詢變得高效應(yīng)該改變數(shù)據(jù)結(jié)構(gòu)。
isAssignableFrom方法的意思是判斷candidateEventType是不是eventType的子類或者子接口飘蚯,如果postSticky()的參數(shù)是子Event,那么@Subscribe注解方法中的參數(shù)是父Event也可以接收到此消息馍迄。

拿到粘性Event后福也,調(diào)用了checkPostStickyEventToSubscription()方法,改方法內(nèi)部方法內(nèi)部調(diào)用了postToSubscription()

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

步驟2總結(jié):至此攀圈,EventBus的注冊操作已經(jīng)全部分析完了暴凑,需要注意的是,粘性事件是在subscribe中進行post的

(二) 發(fā)送事件:EventBus.getDefault().post(xxx);

普通Event

public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
       //  將Event添加到List集合中去
        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 {
               // 遍歷這個list集合赘来,條件是集合是否是空的
                while (!eventQueue.isEmpty()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }

首先將當(dāng)前的 Event添加到eventQueue中去现喳,并且while循環(huán),處理post每一個Event事件犬辰,調(diào)用的是 postSingleEvent(eventQueue.remove(0), postingState);

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        //  獲取Event的Class對象
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;

       //  eventInheritance初始化的時候值為true嗦篱,所以會走該分支
        if (eventInheritance) {
       //  獲取當(dāng)前的Event的Class對象的所有父類的Class對象集合,優(yōu)先從緩存里讀取幌缝。
            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);
        }
    ...
    ...
}

這里lookupAllEventTypes()方法也是為了獲取當(dāng)前的Event的Class對象的所有父類的Class對象集合灸促,優(yōu)先從緩存里讀取。
之后是 for循環(huán)獲取到的Class對象集合狮腿,調(diào)用postSingleEventForEventType()方法腿宰。

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
        // subscriptionsByEventType該map是在subscribe()方法中進行了put操作
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            for (Subscription subscription : subscriptions) {
                postingState.event = event;
                postingState.subscription = subscription;
                boolean aborted = false;
                try {
                   // 進行for循環(huán)并調(diào)用了postToSubscription()
                    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()方法呕诉,主要是獲取Event的Class對象所對應(yīng)的一個List集合缘厢,集合的對象是Subscription參數(shù)。subscriptionsByEventType對象是在subscribe()方法中進行了賦值甩挫。

for循環(huán)CopyOnWriteArrayList集合贴硫,并調(diào)用postToSubscription();

線程模型

等執(zhí)行到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);
        }
    

第一個分支:線程模型是POST,直接調(diào)用了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);
     }
 }

很明顯的看到挖诸,這是基于反射去調(diào)用方法,invoke方法接收兩個參數(shù)法精,第一個參數(shù)是注冊的對象多律,第二個參數(shù)是事件的Event。

從這里就可以看出來搂蜓,POST并沒有去做線程的調(diào)度什么的狼荞,事件處理函數(shù)的線程跟發(fā)布事件的線程在同一個線程。

第二個分支:線程模型是MAIN 首先判斷了下事件發(fā)布的線程是不是主線程帮碰,如果是相味,執(zhí)行invokeSubscriber()方法,invokeSubscriber()上面已經(jīng)分析過殉挽,如果不是主線程丰涉,執(zhí)行mainThreadPoster.enqueue(subscription, event)拓巧。
mainThreadPoster是繼承自Handler,從這里大概可以猜到昔搂,這一步是去做線程調(diào)度的玲销。

我們看一看mainThreadPoster的enqueue做了什么事:

void enqueue(Subscription subscription, Object event) {
        //  封裝了一個PendIngPost
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            // 將PendIngPost壓入隊列
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                //  調(diào)用了sendMessage()
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }

enqueue() 主要封裝了一個PendingPost類,并把subscription和event作為參數(shù)傳進去摘符,緊接著把PendingPost壓入到隊列中去贤斜,然后發(fā)了一條消息sendMessage。

熟悉Handler機制的同學(xué)知道逛裤,處理消息是在handleMessage()方法中完成的:

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

代碼有點多瘩绒,我們主要看一下,它接收到消息后带族,是做了什么處理锁荔。從隊列中取了消息,并且調(diào)用了eventBus.invokeSubscriber(pendingPost)方法蝙砌,回到EventBus類中阳堕。

void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            invokeSubscriber(subscription, event);
        }
    }

該方法內(nèi)部還是去調(diào)用了invokeSubscriber()方法。

分析完線程模型為MAIN 的工作流程择克,不難做出結(jié)論恬总,當(dāng)發(fā)布事件所在的線程是在主線程時,我們不需要做線程調(diào)度肚邢,直接調(diào)用反射方法去執(zhí)行壹堰。如果發(fā)布事件所在的線程不是在主線程,需要使用Handler做線程的調(diào)度骡湖,并最終調(diào)用反射方法去執(zhí)行

第三個分支:線程模型是BACKGROUND贱纠。如果事件發(fā)布的線程是在主線程,執(zhí)行
backgroundPoster.enqueue(subscription, event)响蕴,否則執(zhí)行invokeSubscriber()谆焊。

backgroundPoster實現(xiàn)了Runable接口:

 public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!executorRunning) {
                executorRunning = true;
                eventBus.getExecutorService().execute(this);
            }
        }
    }

將PendingPost對象壓入隊列,然后調(diào)用eventBus.getExecutorService().execute(this)浦夷,交給線程池去進行處理辖试,它的處理是在Runnable的run()中。

@Override
    public void run() {
        try {
            try {
                while (true) {
                    PendingPost pendingPost = queue.poll(1000);
                    if (pendingPost == null) {
                        synchronized (this) {
                            // Check again, this time in synchronized
                            pendingPost = queue.poll();
                            if (pendingPost == null) {
                                executorRunning = false;
                                return;
                            }
                        }
                    }
                    eventBus.invokeSubscriber(pendingPost);
                }
            } catch (InterruptedException e) {
                Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
            }
        } finally {
            executorRunning = false;
        }
    }

最重要的還是eventBus.invokeSubscriber(pendingPost)這行代碼军拟,上面已經(jīng)分析過剃执。

第四個分支:線程模型是ASYNC。直接調(diào)用 asyncPoster.enqueue(subscription, event)懈息,asyncPoster也是實現(xiàn)了Runnable接口肾档,里面也是使用的線程池,具體的操作就不分析了,感興趣的可以去看一下源碼怒见,跟上一步操作類似俗慈。

(三) 高級用法

EventBus3.0較之前的版本有了一次改造,在3.0之后增加了注解處理器遣耍,在程序的編譯時候闺阱,就可以根據(jù)注解生成相對應(yīng)的代碼,相對于之前的直接通過運行時反射舵变,大大提高了程序的運行效率酣溃,但是在3.0默認(rèn)的還是通過反射去查找用@Subscribe標(biāo)注的方法,一般在使用的時候基本都是這個模式纪隙。 那我們怎么配置讓EventBus使用注解器生成的代碼呢赊豌?

EventBus官網(wǎng)apt介紹

在這里我們重點提一下 EventBusBuilder類的:

boolean ignoreGeneratedIndex;
List<SubscriberInfoIndex> subscriberInfoIndexes;

subscriberInfoIndexes變量可以去使用注解處理器生成的代碼。SubscriberInfoIndex 就是一個接口绵咱,而注解生成器生成的類也是繼承的它碘饼,我們也可以自己去繼承它,定制自己的需求悲伶,不需要反射的EventBus艾恼。

我們再回過頭來看一下注冊過程的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);
    }

我們在前面分析的時候,直接分析的 findUsingReflectionInSingleClass(findState)方法麸锉,因為getSubscriberInfo()返回null钠绍,那什么時候getSubscriberInfo()返回不為null呢 ? 我們具體看看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;
           }
       }
      //  判斷subscriberInfoIndexes 是否為null五慈,默認(rèn)為null,當(dāng)我們使用apt插件構(gòu)建代碼 的時候纳寂,可以手動的調(diào)用EventBusBuilder的addIndex主穗,將subscriberInfoIndexes 進行賦值。
       if (subscriberInfoIndexes != null) {
           for (SubscriberInfoIndex index : subscriberInfoIndexes) {
               SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
               if (info != null) {
                   return info;
               }
           }
       }
       return null;
   }

當(dāng)我們使用apt插件構(gòu)建代碼 的時候毙芜,可以手動的調(diào)用EventBusBuilder的addIndex()忽媒,將subscriberInfoIndexes 進行賦值。這樣subscriberInfoIndexes 就不會為null腋粥,getSubscriberInfo()方法也就不會為null晦雨。findUsingInfo()也就不會調(diào)用反射去獲取數(shù)據(jù),從而提高了性能隘冲。

如何使用新特性SubscriberIndex:

在gradle文件做以下配置:

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [ eventBusIndex : 'com.example.myapp.MyEventBusIndex' ]
            }
        }
    }
}

dependencies {
    compile 'org.greenrobot:eventbus:3.1.1'
    annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}

成功構(gòu)建項目后闹瞧,將為您生成使用eventBusIndex指定的類 。然后在設(shè)置EventBus時將其傳遞給它:

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

我們回過頭看展辞,注解器還是很有用的奥邮,避免使用反射去消耗了性能。

總結(jié):無論是EventBus還是ButterKnife,都使用到了注解處理器洽腺,這方面的知識還是要多去學(xué)習(xí)脚粟。還有的是對一個框架不僅僅要知道怎么調(diào)用它的api,還要盡可能的從源碼的角度去分析它的實現(xiàn)原理蘸朋,閱讀源碼也是一個自我提升的一個過程核无!

Android的技術(shù)討論Q群:947460837

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市藕坯,隨后出現(xiàn)的幾起案子团南,更是在濱河造成了極大的恐慌,老刑警劉巖炼彪,帶你破解...
    沈念sama閱讀 217,277評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件已慢,死亡現(xiàn)場離奇詭異,居然都是意外死亡霹购,警方通過查閱死者的電腦和手機佑惠,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,689評論 3 393
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來齐疙,“玉大人膜楷,你說我怎么就攤上這事≌攴埽” “怎么了赌厅?”我有些...
    開封第一講書人閱讀 163,624評論 0 353
  • 文/不壞的土叔 我叫張陵,是天一觀的道長轿塔。 經(jīng)常有香客問我特愿,道長,這世上最難降的妖魔是什么勾缭? 我笑而不...
    開封第一講書人閱讀 58,356評論 1 293
  • 正文 為了忘掉前任揍障,我火速辦了婚禮,結(jié)果婚禮上俩由,老公的妹妹穿的比我還像新娘毒嫡。我一直安慰自己,他們只是感情好幻梯,可當(dāng)我...
    茶點故事閱讀 67,402評論 6 392
  • 文/花漫 我一把揭開白布兜畸。 她就那樣靜靜地躺著,像睡著了一般碘梢。 火紅的嫁衣襯著肌膚如雪咬摇。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,292評論 1 301
  • 那天煞躬,我揣著相機與錄音肛鹏,去河邊找鬼。 笑死,一個胖子當(dāng)著我的面吹牛龄坪,可吹牛的內(nèi)容都是我干的昭雌。 我是一名探鬼主播,決...
    沈念sama閱讀 40,135評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼健田,長吁一口氣:“原來是場噩夢啊……” “哼烛卧!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起妓局,我...
    開封第一講書人閱讀 38,992評論 0 275
  • 序言:老撾萬榮一對情侶失蹤总放,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后好爬,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體局雄,經(jīng)...
    沈念sama閱讀 45,429評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,636評論 3 334
  • 正文 我和宋清朗相戀三年存炮,在試婚紗的時候發(fā)現(xiàn)自己被綠了炬搭。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 39,785評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡穆桂,死狀恐怖宫盔,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情享完,我是刑警寧澤灼芭,帶...
    沈念sama閱讀 35,492評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站般又,受9級特大地震影響彼绷,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜茴迁,卻給世界環(huán)境...
    茶點故事閱讀 41,092評論 3 328
  • 文/蒙蒙 一寄悯、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧笋熬,春花似錦热某、人聲如沸腻菇。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,723評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽筹吐。三九已至糖耸,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間丘薛,已是汗流浹背嘉竟。 一陣腳步聲響...
    開封第一講書人閱讀 32,858評論 1 269
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人舍扰。 一個月前我還...
    沈念sama閱讀 47,891評論 2 370
  • 正文 我出身青樓倦蚪,卻偏偏與公主長得像,于是被迫代替她去往敵國和親边苹。 傳聞我的和親對象是個殘疾皇子陵且,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,713評論 2 354

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