Android EventBus基礎入門及源碼分析

—— 迷茫是什么?迷茫是大事干不了,小事不想干。能力配不上欲望,才華配不上夢想。

前言

時隔多年,那些曾經學過且用過的知識早已記憶模糊。如果不反復研究學習,使用起來也會很生澀,如新知識一樣。本編為鞏固EventBus所寫。一個人為什么要努力,因為喜歡的東西很貴想去的地方都很遠,想愛的人很完美。

一、簡介

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

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

(1)是什么:是一個事件發布/訂閱的輕量級框架。基于觀察者模式,實現組件間的通訊。代碼簡潔且解耦。

(2)有什么用:可以替代傳統的Intent,Handler,Broadcast或接口函數。

?二、基本使用

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

implementation 'org.greenrobot:eventbus:3.0.0'

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

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

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

@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)發送事件

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

簡單的整理了一下 。正確姿勢參考官方文檔。

三、源碼分析

(1)EventBus.getDefault()

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

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

    * 屬性簡介
   EventBus(EventBusBuilder builder) {
        * 保存Event集合
        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;
        * EventBus訂閱方法
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        * EventBus日志
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        * 無消息發送
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        * 異常事件
        throwSubscriberException = builder.throwSubscriberException;
        * EventBus繼承關系
        eventInheritance = builder.eventInheritance;
        * 線程池
        executorService = builder.executorService;
    }

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

* 注冊給定的訂閱方以接收事件
public void register(Object subscriber) {
    * 利用反射獲取訂閱的類
    Class<?> subscriberClass = subscriber.getClass();
    * 根據訂閱的類找到 該類下的訂閱方法   -> 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 忽略生成的索引 默認為false
    if (ignoreGeneratedIndex) {
        subscriberMethods = findUsingReflection(subscriberClass);
    } else {
        * 通過反射獲取到訂閱方法列表 -> 1.1
        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;
    }
}

1.1.findUsingInfo(Class<?> subscriberClass)

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

2.subscribe(Object subscriber, SubscriberMethod subscriberMethod)

* 判斷是否已經注冊/訂閱過該事件
* 按照優先級緩存訂閱事件
* 判斷是否已經緩存在typesBySubscriber中 
* 判斷是否是粘性事件  并分發粘性事件

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    * 訂閱方法類型
    Class&lt<?> 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);
        }
    }
    * 按照優先級緩存訂閱事件  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;
        }
    }
    * 判斷是否已經緩存在typesBySubscriber中  
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);
    * 判斷是否是粘性事件  并分發粘性事件
    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();
                    * 分發事件
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = stickyEvents.get(eventType);
            * 分發事件  -->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());
    }
}
* 根據線程模式進行事件分發
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);
    }
}

* 利用反射 執行訂閱方法
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 隊列中  執行handler 從隊列沖取出消息進行處理 并利用反射 執行訂閱方法 
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");
            }
        }
    }
}

總結:

1.利用反射獲取到訂閱類的所有訂閱方法

2.判斷是否已經注冊/訂閱過該事件

3.按照優先級緩存訂閱事件

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

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

* 發送事件
public void post(Object event) {
    * 獲取當前線程的信息
    PostingThreadState postingState = currentPostingThreadState.get();
    * 將事件添加到當前線程的隊列中
    List<Object> eventQueue = postingState.eventQueue;
    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 {
            while (!eventQueue.isEmpty()) {
                * 循環分發事件 -->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;
    * 判斷是否有繼承關系
    if (eventInheritance) {
        * 獲取所有類的對象 包含父類與接口
        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);
    }
    * 若沒有找到訂閱方法 則調用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;
}

總結:

1.獲取當前線程的信息,將事件添加到當前線程的隊列中

2.判斷是否正在分發 不是則執行postSingleEvent 分發事件

3.判斷是否有繼承關系

是:獲取所有類的對象 包含父類與接口 調用postSingleEventForEventType分發事件

否:調用postSingleEventForEventType分發事件

4.若沒有找到訂閱方法 則分發給NoSubscriberEvent

介紹到這里就結束了 睡覺去了

四、內容推薦

若您發現文章中存在錯誤或不足的地方,希望您能指出!

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,563評論 6 544
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,694評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,672評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,965評論 1 318
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,690評論 6 413
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 56,019評論 1 329
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 44,013評論 3 449
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,188評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,718評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,438評論 3 360
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,667評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,149評論 5 365
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,845評論 3 351
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,252評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,590評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,384評論 3 400
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,635評論 2 380

推薦閱讀更多精彩內容

  • 前言 成為一名優秀的Android開發,需要一份完備的知識體系,在這里,讓我們一起成長為自己所想的那樣~。 不知不...
    hpc閱讀 642評論 0 0
  • EventBus是一款用于傳遞事件的開源框架,首次使用就被其極低的耦合性給折服,同時它也支持訂閱方法的線程指定。最...
    zskingking閱讀 591評論 0 8
  • 功能 EventBus 是一個 Android 事件發布/訂閱框架,通過解耦發布者和訂閱者簡化 Android 事...
    maimingliang閱讀 1,187評論 0 14
  • EventBus源碼分析 Android開發中我們最常用到的可以說就是EventBus了,今天我們來深入研究一下E...
    BlackFlag閱讀 513評論 3 4
  • 流程分析 EventBus 是一個發布 / 訂閱的事件總線,總線可以有一個也可以有多個。總共包含4個成分:發布者,...
    thomasyoungs閱讀 221評論 0 0