EventBus源碼分析(二)

前面已經(jīng)說了EventBus的基本用法,下面我們一步步的看下Eventbus中到底做了些什么,為什么使用Index就讓性能得到了提升探孝。

注冊

1、獲取EventBus實例

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

通過這種雙重校驗鎖的方式獲取單例神帅,當(dāng)然獲取實例的方式還有其他方法再姑,但是強烈建議你使用這種方式,否則你會遇到一項不到的事情找御。

2元镀、注冊

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    //  查找注冊類中監(jiān)聽的方法(通過注解或者索引)
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            //  注冊方法
            subscribe(subscriber, subscriberMethod);
        }
    }
}

在注冊時,首先會通過SubscriberMethodFiner屬性的findSubscriberMethods方法找到訂閱者所有的訂閱方法霎桅;然后遍歷訂閱方法栖疑,對統(tǒng)一訂閱統(tǒng)一類型消息的方法在一個集合里;訂閱類和訂閱方法放在map中做一個映射滔驶,方便后邊的反注冊遇革。

3、SubscriberMethodFinder查找方法

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    //  默認為false,只有指定ignoreGeneratedIndex=true才會為true
    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;
    }
}

SubscriberMethodFinder的findSubscriberMethods首先會通過緩存找到揭糕,找到了就返回萝快,找不到就繼續(xù)找,查找方式有兩種反射和索引著角,主要通過ignoreGeneratedIndex揪漩,這個屬性默認為false,首先進行索引找到吏口,索引未找到時才會啟動反射查找

4奄容、反射查找

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        findUsingReflectionInSingleClass(findState);
        findState.moveToSuperclass();
    }
    return getMethodsAndRelease(findState);
}

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

反射遍歷每一個方法,然后通過注解和參數(shù)進行校驗产徊,放在FindState的subscriberMethods集合里面

5昂勒、使用索引查找

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

重點是在findUsingInfo里面調(diào)用了getSubscriberInfo方法,這個方法遍歷調(diào)用索引的getSubscriberInfo方法舟铜,返回空則進行下一個戈盈,不為空直接返回結(jié)果。如果查找了所有的索引都沒有那么會使用findUsingReflectionInSingleClass使用反射查找谆刨,那遍歷的索引是在EventBusBuilder
的addIndex方法中加入的奕谭。

6、找到方法之后痴荐,還要進行注冊血柳,這里一步是方便后面的發(fā)布消息以及取消注冊的操作

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<>();
        //  方便發(fā)送消息的操作
        subscriptionsByEventType.put(eventType, subscriptions);
    }
    //  省略部分代碼

    //  優(yōu)先級
    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);

}

這里主要有兩個Map:subscriptionsByEventType和typesBySubscriber,消息函數(shù)參數(shù)->所有的訂閱方法生兆,訂閱類->訂閱方法难捌。到此EventBus的注冊功能結(jié)結(jié)束了,我們來看下他的時序圖

消息發(fā)送

1鸦难、通過調(diào)用EventBus的post方法即可完成消息的發(fā)送根吁,在post方法中調(diào)用了postSingleEvent方法,postSingleEvent方法會繼續(xù)調(diào)用postSingleEventForEventType方法

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    synchronized (this) {
        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;
            } finally {
                postingState.event = null;
                postingState.subscription = null;
                postingState.canceled = false;
            }
            if (aborted) {
                break;
            }
        }
        return true;
    }
    return false;
}

postSingleEventForEventType方法通過subscriptionsByEventType獲取消息類型對應(yīng)的Subscription集合,Subscription封裝了實例和訂閱方法名合蔽,這樣我們就可以進行調(diào)用了击敌。

2、執(zhí)行訂閱方法拴事,找到Subscription之后沃斤,就會遍歷執(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);
    }
}

在此方法中會根據(jù)Subscription的threadMode來執(zhí)行圣蝎,我們最常用的就Main,我們看到如果當(dāng)前是主線程會直接執(zhí)行衡瓶,如果不是主線程會使用mainThreadPoster徘公,其實這是一個主進程的Handler,這也是為什么我們可以在threadMode=main的訂閱方法中操作UI的原因

3、HandlerPoster的enqueue方法哮针,發(fā)送消息

void enqueue(Subscription subscription, Object event) {
    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");
            }
        }
    }
}

首先這里先封裝成PendingPost关面,然后加入隊列,發(fā)送一個空的消息十厢,為啥要這樣搞呢等太?可能是因為直接發(fā)送一個消息過去,不方便傳遞Subscription和Event吧蛮放。

4缩抡、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)用EvenBus的invokeSubscriber方法筛武。這里應(yīng)該是真正執(zhí)行訂閱方法的地方

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

OK缝其,在這里執(zhí)行了invoke方法,訂閱方法被調(diào)用了徘六。

EventBus反注冊

public synchronized void unregister(Object subscriber) {
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

包括一下幾個步驟:
1内边、找到訂閱類訂閱的消息類型
2、遍歷消息類型待锈,找到消息類型對應(yīng)的所有的訂閱方法
3漠其、遍歷所有訂閱方法,如果實例等于這個反注冊的訂閱類的進行去除操作(unsubscribeByEventType方法)
4竿音、去除訂閱類到訂閱消息類型的映射

在使用EventBus過程中和屎,一定要取消訂閱,否則會導(dǎo)致內(nèi)存泄漏春瞬。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末柴信,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子宽气,更是在濱河造成了極大的恐慌随常,老刑警劉巖,帶你破解...
    沈念sama閱讀 222,183評論 6 516
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件萄涯,死亡現(xiàn)場離奇詭異绪氛,居然都是意外死亡,警方通過查閱死者的電腦和手機涝影,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,850評論 3 399
  • 文/潘曉璐 我一進店門枣察,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事序目”酆郏” “怎么了?”我有些...
    開封第一講書人閱讀 168,766評論 0 361
  • 文/不壞的土叔 我叫張陵宛琅,是天一觀的道長刻蟹。 經(jīng)常有香客問我逗旁,道長嘿辟,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 59,854評論 1 299
  • 正文 為了忘掉前任片效,我火速辦了婚禮红伦,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘淀衣。我一直安慰自己昙读,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 68,871評論 6 398
  • 文/花漫 我一把揭開白布膨桥。 她就那樣靜靜地躺著蛮浑,像睡著了一般。 火紅的嫁衣襯著肌膚如雪只嚣。 梳的紋絲不亂的頭發(fā)上沮稚,一...
    開封第一講書人閱讀 52,457評論 1 311
  • 那天矢赁,我揣著相機與錄音峰弹,去河邊找鬼彭沼。 笑死裆熙,一個胖子當(dāng)著我的面吹牛耘眨,可吹牛的內(nèi)容都是我干的袍镀。 我是一名探鬼主播翼闽,決...
    沈念sama閱讀 40,999評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼倦零,長吁一口氣:“原來是場噩夢啊……” “哼藐石!你這毒婦竟也來了即供?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,914評論 0 277
  • 序言:老撾萬榮一對情侶失蹤于微,失蹤者是張志新(化名)和其女友劉穎逗嫡,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體角雷,經(jīng)...
    沈念sama閱讀 46,465評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡祸穷,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,543評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了勺三。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片雷滚。...
    茶點故事閱讀 40,675評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖吗坚,靈堂內(nèi)的尸體忽然破棺而出祈远,到底是詐尸還是另有隱情呆万,我是刑警寧澤,帶...
    沈念sama閱讀 36,354評論 5 351
  • 正文 年R本政府宣布车份,位于F島的核電站谋减,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏扫沼。R本人自食惡果不足惜出爹,卻給世界環(huán)境...
    茶點故事閱讀 42,029評論 3 335
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望缎除。 院中可真熱鬧严就,春花似錦、人聲如沸器罐。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,514評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽轰坊。三九已至铸董,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間肴沫,已是汗流浹背粟害。 一陣腳步聲響...
    開封第一講書人閱讀 33,616評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留樊零,地道東北人我磁。 一個月前我還...
    沈念sama閱讀 49,091評論 3 378
  • 正文 我出身青樓,卻偏偏與公主長得像驻襟,于是被迫代替她去往敵國和親夺艰。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,685評論 2 360

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