Android EventBus基礎(chǔ)入門(mén)及源碼分析

—— 迷茫是什么荷鼠?迷茫是大事干不了句携,小事不想干。能力配不上欲望允乐,才華配不上夢(mèng)想矮嫉。

前言

時(shí)隔多年削咆,那些曾經(jīng)學(xué)過(guò)且用過(guò)的知識(shí)早已記憶模糊。如果不反復(fù)研究學(xué)習(xí)蠢笋,使用起來(lái)也會(huì)很生澀拨齐,如新知識(shí)一樣。本編為鞏固EventBus所寫(xiě)昨寞。一個(gè)人為什么要努力瞻惋,因?yàn)橄矚g的東西很貴想去的地方都很遠(yuǎn),想愛(ài)的人很完美援岩。

一歼狼、簡(jiǎn)介

官方文檔:https://greenrobot.org/eventbus/documentation/

Github:https://github.com/greenrobot/EventBus

(1)是什么:是一個(gè)事件發(fā)布/訂閱的輕量級(jí)框架∠砘常基于觀察者模式羽峰,實(shí)現(xiàn)組件間的通訊。代碼簡(jiǎn)潔且解耦添瓷。

(2)有什么用:可以替代傳統(tǒng)的Intent,Handler,Broadcast或接口函數(shù)梅屉。

?二、基本使用

(1)添加依賴 (不是最新) 基于以前學(xué)過(guò)的版本

implementation 'org.greenrobot:eventbus:3.0.0'

(2)定義消息事件(可以配置傳遞參數(shù))

public static class MessageEvent { /* Additional fields if needed */ }

(3)定義接收事件的線程方法(發(fā)送的事件鳞贷,將在該方法中收到)

@Subscribe(threadMode = ThreadMode.MAIN)  
public void onMessageEvent(MessageEvent event) {/* Do something */};

(4)EventBus初始化 (與廣播相似坯汤,需要訂閱與取消)

 @Override
 public void onStart() {
     super.onStart();
     EventBus.getDefault().register(this);
 }

 @Override
 public void onStop() {
     super.onStop();
     EventBus.getDefault().unregister(this);
 }

(5)發(fā)送事件

EventBus.getDefault().post(new MessageEvent());

(6)添加混淆

-keepattributes *Annotation*
-keepclassmembers class * {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }

# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);
}

簡(jiǎn)單的整理了一下 。正確姿勢(shì)參考官方文檔搀愧。

三惰聂、源碼分析

(1)EventBus.getDefault()

* 單例模式 雙重效驗(yàn)鎖  線程安全 懶加載
public static EventBus getDefault() {
   if (defaultInstance == null) {
       synchronized (EventBus.class) {
          if (defaultInstance == null) {
              defaultInstance = new EventBus();
          }
       }
    }
    return defaultInstance;
}

* 使用構(gòu)建者配置EventBus 屬性
    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
    public EventBus() {
        this(DEFAULT_BUILDER);
    }

    * 屬性簡(jiǎn)介
   EventBus(EventBusBuilder builder) {
        * 保存Event集合
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        * 線程調(diào)度
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        * 索引
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        * EventBus訂閱方法
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        * EventBus日志
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        * 無(wú)消息發(fā)送
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        * 異常事件
        throwSubscriberException = builder.throwSubscriberException;
        * EventBus繼承關(guān)系
        eventInheritance = builder.eventInheritance;
        * 線程池
        executorService = builder.executorService;
    }

(2)EventBus.getDefault().register(this)

* 注冊(cè)給定的訂閱方以接收事件
public void register(Object subscriber) {
    * 利用反射獲取訂閱的類(lèi)
    Class<?> subscriberClass = subscriber.getClass();
    * 根據(jù)訂閱的類(lèi)找到 該類(lèi)下的訂閱方法   -> 1
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        * 便利所有的訂閱方法
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
                        * --> 2
            subscribe(subscriber, subscriberMethod);
        }
    }
}

1.subscriberMethodFinder.findSubscriberMethods(subscriberClass)

* 獲取所有的訂閱方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    * 判斷是否已緩存
    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
    if (subscriberMethods != null) {
        return subscriberMethods;
    }
    * ignoreGeneratedIndex 忽略生成的索引 默認(rèn)為false
    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        * 通過(guò)反射獲取到訂閱方法列表 -> 1.1
        subscriberMethods = findUsingInfo(subscriberClass);
    }
    * 訂閱方法列表為空時(shí) 拋出異常
    if (subscriberMethods.isEmpty()) {
        throw new EventBusException("Subscriber" + subscriberClass
                + " and its super classes have no public methods with the @Subscribe annotation");
    } else {
        * 緩存該訂閱類(lèi)的所有訂閱方法
        METHOD_CACHE.put(subscriberClass, subscriberMethods);
        return subscriberMethods;
    }
}

1.1.findUsingInfo(Class<?> subscriberClass)

* 通過(guò)反射獲取到訂閱方法列表
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    * 創(chuàng)建FindState 并初始化
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        * 判斷findState是否已經(jīng)有緩存訂閱信息
        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 {
            * 利用反射機(jī)制 將訂閱方法信息 存儲(chǔ)在findState 中
            findUsingReflectionInSingleClass(findState);
        }
        * 移除訂閱類(lèi)
        findState.moveToSuperclass();
    }
    * 回收FindState對(duì)象,獲取訂閱方法列表
    return getMethodsAndRelease(findState);
}

2.subscribe(Object subscriber, SubscriberMethod subscriberMethod)

* 判斷是否已經(jīng)注冊(cè)/訂閱過(guò)該事件
* 按照優(yōu)先級(jí)緩存訂閱事件
* 判斷是否已經(jīng)緩存在typesBySubscriber中 
* 判斷是否是粘性事件  并分發(fā)粘性事件

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    * 訂閱方法類(lèi)型
    Class&lt<?> eventType = subscriberMethod.eventType;
    * 創(chuàng)建 訂閱事件
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    * 判斷是否緩存過(guò) 訂閱事件 列表
    CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<>();
        subscriptionsByEventType.put(eventType, subscriptions);
    } else {
        * 判斷是否已經(jīng)訂閱過(guò)  訂閱過(guò)則拋出異常
        if (subscriptions.contains(newSubscription)) {
            throw new EventBusException("Subscriber" + subscriber.getClass() + " already registered to event "+ eventType);
        }
    }
    * 按照優(yōu)先級(jí)緩存訂閱事件  subscriptionsByEventType
    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;
        }
    }
    * 判斷是否已經(jīng)緩存在typesBySubscriber中  
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);
    * 判斷是否是粘性事件  并分發(fā)粘性事件
    if (subscriberMethod.sticky) {
        if (eventInheritance) {
            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();
                    * 分發(fā)事件
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = stickyEvents.get(eventType);
            * 分發(fā)事件  -->2.1
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

2.1checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent)

 * 判斷粘性事件是否為空  
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());
    }
}
* 根據(jù)線程模式進(jìn)行事件分發(fā)
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);
    }
}

* 利用反射 執(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);
    }
}

*  將事件添加到 PendingPostQueue 隊(duì)列中  執(zhí)行handler 從隊(duì)列沖取出消息進(jìn)行處理 并利用反射 執(zhí)行訂閱方法 
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");
            }
        }
    }
}

總結(jié):

1.利用反射獲取到訂閱類(lèi)的所有訂閱方法

2.判斷是否已經(jīng)注冊(cè)/訂閱過(guò)該事件

3.按照優(yōu)先級(jí)緩存訂閱事件

4.判斷是否是粘性事件 并分發(fā)粘性事件 (1)同一個(gè)線程 利用反射 執(zhí)行訂閱方法 (2)不同線程 將事件添加到 PendingPostQueue 隊(duì)列中 執(zhí)行handler 從隊(duì)列沖取出消息進(jìn)行處理 并利用反射 執(zhí)行訂閱方法

(3)EventBus.getDefault().post(new MessageEvent());

* 發(fā)送事件
public void post(Object event) {
    * 獲取當(dāng)前線程的信息
    PostingThreadState postingState = currentPostingThreadState.get();
    * 將事件添加到當(dāng)前線程的隊(duì)列中
    List<Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);
    * 判斷是否正在分發(fā)  不是則繼續(xù)執(zhí)行
    if (!postingState.isPosting) {
        postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
        postingState.isPosting = true;
        * 判斷是否被取消
        if (postingState.canceled) {
            throw new EventBusException("Internal error. Abort state was not reset");
        }
        try {
            while (!eventQueue.isEmpty()) {
                * 循環(huán)分發(fā)事件 -->1
                postSingleEvent(eventQueue.remove(0), postingState);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}

1.postSingleEvent(eventQueue.remove(0), postingState);

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    * 判斷是否有繼承關(guān)系
    if (eventInheritance) {
        * 獲取所有類(lèi)的對(duì)象 包含父類(lèi)與接口
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);   
                        * --> 2
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
    * 若沒(méi)有找到訂閱方法 則調(diào)用NoSubscriberEvent
    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));
        }
    }
}

2.postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass)

* 從subscriptionsByEventType中獲取訂閱方法
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;
}

總結(jié):

1.獲取當(dāng)前線程的信息咱筛,將事件添加到當(dāng)前線程的隊(duì)列中

2.判斷是否正在分發(fā) 不是則執(zhí)行postSingleEvent 分發(fā)事件

3.判斷是否有繼承關(guān)系

是:獲取所有類(lèi)的對(duì)象 包含父類(lèi)與接口 調(diào)用postSingleEventForEventType分發(fā)事件

否:調(diào)用postSingleEventForEventType分發(fā)事件

4.若沒(méi)有找到訂閱方法 則分發(fā)給NoSubscriberEvent

介紹到這里就結(jié)束了 睡覺(jué)去了

四庶近、內(nèi)容推薦

若您發(fā)現(xiàn)文章中存在錯(cuò)誤或不足的地方,希望您能指出眷蚓!

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市反番,隨后出現(xiàn)的幾起案子沙热,更是在濱河造成了極大的恐慌,老刑警劉巖罢缸,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件篙贸,死亡現(xiàn)場(chǎng)離奇詭異,居然都是意外死亡枫疆,警方通過(guò)查閱死者的電腦和手機(jī)爵川,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門(mén),熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)息楔,“玉大人寝贡,你說(shuō)我怎么就攤上這事扒披。” “怎么了圃泡?”我有些...
    開(kāi)封第一講書(shū)人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵碟案,是天一觀的道長(zhǎng)。 經(jīng)常有香客問(wèn)我颇蜡,道長(zhǎng)价说,這世上最難降的妖魔是什么? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任风秤,我火速辦了婚禮鳖目,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘缤弦。我一直安慰自己领迈,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布甸鸟。 她就那樣靜靜地躺著惦费,像睡著了一般。 火紅的嫁衣襯著肌膚如雪抢韭。 梳的紋絲不亂的頭發(fā)上薪贫,一...
    開(kāi)封第一講書(shū)人閱讀 51,692評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音刻恭,去河邊找鬼瞧省。 笑死,一個(gè)胖子當(dāng)著我的面吹牛鳍贾,可吹牛的內(nèi)容都是我干的鞍匾。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼骑科,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼橡淑!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起咆爽,我...
    開(kāi)封第一講書(shū)人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤梁棠,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后斗埂,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體符糊,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年呛凶,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了男娄。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖模闲,靈堂內(nèi)的尸體忽然破棺而出建瘫,到底是詐尸還是另有隱情,我是刑警寧澤围橡,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布暖混,位于F島的核電站,受9級(jí)特大地震影響翁授,放射性物質(zhì)發(fā)生泄漏拣播。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一收擦、第九天 我趴在偏房一處隱蔽的房頂上張望贮配。 院中可真熱鬧,春花似錦塞赂、人聲如沸泪勒。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)圆存。三九已至,卻和暖如春仇哆,著一層夾襖步出監(jiān)牢的瞬間沦辙,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來(lái)泰國(guó)打工讹剔, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留油讯,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓延欠,卻偏偏與公主長(zhǎng)得像陌兑,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子由捎,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

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

  • 前言 成為一名優(yōu)秀的Android開(kāi)發(fā)兔综,需要一份完備的知識(shí)體系,在這里狞玛,讓我們一起成長(zhǎng)為自己所想的那樣~邻奠。 不知不...
    hpc閱讀 632評(píng)論 0 0
  • EventBus是一款用于傳遞事件的開(kāi)源框架,首次使用就被其極低的耦合性給折服为居,同時(shí)它也支持訂閱方法的線程指定。最...
    zskingking閱讀 582評(píng)論 0 8
  • 功能 EventBus 是一個(gè) Android 事件發(fā)布/訂閱框架杀狡,通過(guò)解耦發(fā)布者和訂閱者簡(jiǎn)化 Android 事...
    maimingliang閱讀 1,182評(píng)論 0 14
  • EventBus源碼分析 Android開(kāi)發(fā)中我們最常用到的可以說(shuō)就是EventBus了蒙畴,今天我們來(lái)深入研究一下E...
    BlackFlag閱讀 509評(píng)論 3 4
  • 流程分析 EventBus 是一個(gè)發(fā)布 / 訂閱的事件總線,總線可以有一個(gè)也可以有多個(gè)∩拍總共包含4個(gè)成分:發(fā)布者碑隆,...
    thomasyoungs閱讀 217評(píng)論 0 0