事件總線-EventBus-源碼學習過程

使用過程略過滑燃。

源碼分析

register方法:
1、獲取注冊對象類型
2颓鲜、獲取對象的所有的訂閱方法的集合
3表窘、遍歷集合,執(zhí)行訂閱subscribe方法甜滨。

/**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * <p/>
     * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

SubscriberMethod類包含訂閱方法的所有信息乐严,Method對象,參數(shù)類型费变,執(zhí)行的線程董虱,優(yōu)先級券躁,是否粘性

public class SubscriberMethod {
    final Method method;//Method
    final ThreadMode threadMode;//執(zhí)行的線程
    final Class<?> eventType;//方法參數(shù)的EventType
    final int priority;//優(yōu)先級
    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集合的獲取邏輯:

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

findSubscriberMethods實現(xiàn)

    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;
        }
    }```
分為使用索引和忽略索引兩個方法的內容,使用索引的后面單獨了解既琴。忽略索引的邏輯,F(xiàn)indState查找?guī)椭惻葑臁@锩娴腸heckAll甫恩、checkAddWithMethodSignature、moveToSuperclass這三個方法很有趣酌予,使用的map.put返回“前任”邏輯磺箕,巧妙的實現(xiàn)了對象是否被添加過的判斷纹腌。

static class FindState {
//所有訂閱方法的集合
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
//事件類型是已經存在的標識map
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
//方法key和方法所屬的類組成的標識map
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
//產生方法key的builder
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;
    }

    void recycle() {
        subscriberMethods.clear();
        anyMethodByEventType.clear();
        subscriberClassByMethodKey.clear();
        methodKeyBuilder.setLength(0);
        subscriberClass = null;
        clazz = null;
        skipSuperClasses = false;
        subscriberInfo = null;
    }

    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) {
            //沒有添加,返回true
            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);
        }
    }

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

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

findUsingReflection:將訂閱對象中所有打了標記的Subscribe的訂閱方法,全部添加到findState的subscriberMethods中滞磺,然后通過getMethodsAndRelease升薯,返回所有的訂閱方法集合,并且將findState的對象放回對象池击困。
查找方法集合后涎劈,返回EventBus執(zhí)行注冊的邏輯。

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

//添加到集合阅茶,并且按照優(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;
}
}```
這里用到有兩個Cache:
1蛛枚、subscriptionsByEventType=EventType:Subscriptions(subscriber+subscriberMethod)
2、typesBySubscriber=obj:EventTypes
通過事件脸哀,快速定位到訂閱者+訂閱方法對象蹦浦;通過訂閱者,獲取它所訂閱的所有事件類型集合撞蜂。
粘性事件下一章再說盲镶。
注冊到些為止。

unregister:通過typesBySubscriber獲取所有注冊的事件類型蝌诡。然后通過subscriptionsByEventType獲取每個事件類型對應該的訂閱器集合溉贿,遍歷每個訂閱器,判斷是否為當前對象浦旱,如果是宇色,移除。

post:先看PostingThreadState類用來說明當前執(zhí)行的線程事件的執(zhí)行狀態(tài)颁湖。

final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<Object>();//為什么沒有用實現(xiàn)隊列的LinkedList呢宣蠕?
        boolean isPosting;
        boolean isMainThread;
        Subscription subscription;
        Object event;
        boolean canceled;
    }```
一個本地線程包裝器,把PostingThreadState包裝一下甥捺。

private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};```
執(zhí)行postSingleEvent里面有一個lookupAllEventTypes方法抢蚀,獲取事件參數(shù)對應的所有接口的類型。放到緩存eventTypesCache中涎永。

private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
        synchronized (eventTypesCache) {
            List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
            if (eventTypes == null) {
                eventTypes = new ArrayList<>();
                Class<?> clazz = eventClass;
                while (clazz != null) {
                    eventTypes.add(clazz);
                    addInterfaces(eventTypes, clazz.getInterfaces());//添加所有父類接口類型
                    clazz = clazz.getSuperclass();
                }
                eventTypesCache.put(eventClass, eventTypes);
            }
            return eventTypes;
        }
    }```
接下來是postSingleEventForEventType具體的發(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);
}```
里面的postToSubscription方法,根據(jù)訂閱方法指定的線程模式羡微,執(zhí)行相應的邏輯谷饿。

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;
    }
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);
        }
    }```
invokeSubscriber方法就是反射執(zhí)行方法。

執(zhí)行過程:
將要發(fā)送的對象:PendingPost妈倔,還有隊列PendingPostQueue博投。
mainThread對應的執(zhí)行對象:HandlerPoster

void enqueue(Subscription subscription, Object event) {
//緩存獲取發(fā)送對象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
//加入到執(zhí)行隊列里面
queue.enqueue(pendingPost);
//是否正在執(zhí)行
if (!handlerActive) {
handlerActive = true;
//發(fā)送主線程消息
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}

@Override
public void handleMessage(Message msg) {
    boolean rescheduled = false;//是否執(zhí)行超時
    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;
    }
}```

BackgroundPoster:

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

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

AsyncPoster

public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}```
這三個poster都是大同小異,獲取執(zhí)行隊列盯蝴。然后循環(huán)執(zhí)行毅哗。

接下分析一下粘性事件:事件A已經發(fā)送完畢听怕,然后注冊一個訂閱A的粘性事件SB,那么立即還會向SB發(fā)送事件A虑绵∧虿t;谶@個邏輯分析,那么粘性事件一定是在注冊的時候翅睛。查看register的方法声搁。

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();
//如果注冊事件的類型在粘性事件的緩存里面執(zhí)行checkPostStickyEventToSubscription
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }```
checkPostStickyEventToSubscription最終執(zhí)行postToSubscription方法。
stickyEvents是在那里添加的呢捕发?EventBus并不是所有的事件都是粘性的疏旨,只有使用postSticky來發(fā)送的事件,才會被緩存下來扎酷。

接下來分析(兩個晚上檐涝,現(xiàn)在又到12:10分了,明天一定要弄完):索引的那部分邏輯法挨,知識比較多谁榜。

通過注解反身獲取訂閱對象的所有訂閱方法,會消耗一定的性能坷剧,所以EventBus在編譯期提供了生成代碼的邏輯惰爬,把注解的方法,統(tǒng)一生成代碼惫企。運行期直接注冊,就是我們將要分析的索引邏輯陵叽。
里面有一些元數(shù)據(jù)的概念狞尔,用來描述對象的屬性信息,各種info類巩掺,然后通過代碼MyEventBusIndex類(build里面)偏序。可以查看EventBusAnnotationProcessor代碼生成邏輯胖替。

參考:
http://www.cnblogs.com/all88/archive/2016/03/30/5338412.html
http://www.reibang.com/p/f057c460c77e
http://kymjs.com/code/2015/12/12/01
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末研儒,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子独令,更是在濱河造成了極大的恐慌端朵,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,820評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件燃箭,死亡現(xiàn)場離奇詭異冲呢,居然都是意外死亡,警方通過查閱死者的電腦和手機招狸,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,648評論 3 399
  • 文/潘曉璐 我一進店門敬拓,熙熙樓的掌柜王于貴愁眉苦臉地迎上來邻薯,“玉大人,你說我怎么就攤上這事乘凸〔薰睿” “怎么了?”我有些...
    開封第一講書人閱讀 168,324評論 0 360
  • 文/不壞的土叔 我叫張陵营勤,是天一觀的道長木人。 經常有香客問我,道長冀偶,這世上最難降的妖魔是什么醒第? 我笑而不...
    開封第一講書人閱讀 59,714評論 1 297
  • 正文 為了忘掉前任,我火速辦了婚禮进鸠,結果婚禮上稠曼,老公的妹妹穿的比我還像新娘。我一直安慰自己客年,他們只是感情好霞幅,可當我...
    茶點故事閱讀 68,724評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著量瓜,像睡著了一般司恳。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上绍傲,一...
    開封第一講書人閱讀 52,328評論 1 310
  • 那天扔傅,我揣著相機與錄音,去河邊找鬼烫饼。 笑死猎塞,一個胖子當著我的面吹牛,可吹牛的內容都是我干的杠纵。 我是一名探鬼主播荠耽,決...
    沈念sama閱讀 40,897評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼比藻!你這毒婦竟也來了铝量?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 39,804評論 0 276
  • 序言:老撾萬榮一對情侶失蹤银亲,失蹤者是張志新(化名)和其女友劉穎慢叨,沒想到半個月后,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體群凶,經...
    沈念sama閱讀 46,345評論 1 318
  • 正文 獨居荒郊野嶺守林人離奇死亡插爹,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 38,431評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赠尾。...
    茶點故事閱讀 40,561評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡力穗,死狀恐怖,靈堂內的尸體忽然破棺而出气嫁,到底是詐尸還是另有隱情当窗,我是刑警寧澤,帶...
    沈念sama閱讀 36,238評論 5 350
  • 正文 年R本政府宣布寸宵,位于F島的核電站崖面,受9級特大地震影響,放射性物質發(fā)生泄漏梯影。R本人自食惡果不足惜巫员,卻給世界環(huán)境...
    茶點故事閱讀 41,928評論 3 334
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望甲棍。 院中可真熱鬧简识,春花似錦、人聲如沸感猛。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,417評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽陪白。三九已至颈走,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間咱士,已是汗流浹背立由。 一陣腳步聲響...
    開封第一講書人閱讀 33,528評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留司致,地道東北人拆吆。 一個月前我還...
    沈念sama閱讀 48,983評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像脂矫,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子霉晕,可洞房花燭夜當晚...
    茶點故事閱讀 45,573評論 2 359

推薦閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理庭再,服務發(fā)現(xiàn),斷路器牺堰,智...
    卡卡羅2017閱讀 134,702評論 18 139
  • EventBus用法及源碼解析目錄介紹1.EventBus簡介1.1 EventBus的三要素1.2 EventB...
    楊充211閱讀 1,899評論 0 4
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 172,290評論 25 707
  • 腦海中第一次閃出來這個表達拄轻,是兩天前在領受校長,也就是老板對于我的表現(xiàn)和狀態(tài)有些許不滿的時候伟葫。 在此之前恨搓,我從來沒...
    小樂心閱讀 356評論 0 1
  • 雖然是寫給M的信,但在寫信的過程里,我卻逐漸意識到斧抱,在愛里常拓,我們都太自私了。這自私讓我們變得渺小卻自以為是辉浦,這自私...
    半山小院兒閱讀 556評論 0 2