EventBus的核心工做機制以下圖java
在EventBus3.0架構圖:架構
在EventBus3.0框架的內部,核心類就是EventBus,訂閱者的註冊/訂閱,解除註冊,以及事件的分發所有在這個核心類中實現;框架
對於EventBus對象的建立,在框架內部是經過單例模式進行建立;咱們平時在代碼中經過EventBus類中的靜態方法getDefault 獲取實例對象;異步
public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; } public EventBus() { this(DEFAULT_BUILDER); }
從代碼中能夠看出在建立EventBus對象的時候內部會初始化一些字段的配置,在EventBus類內部存在許多的Map字段;當post分發時,就是從這些map中查詢出相應的消息處理事件;async
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType: key:爲咱們自定義的事件類,value:訂閱者的回調方法列表,subscriptionsByEventType 在訂閱者進行訂閱/註冊時添加相應的map關係;當EventBus接收到一個事件時,會在subscriptionsByEventType 中根據事件類型查找出全部監聽了這個時間的訂閱者和回調方法等信息;咱們知道Subscription類中包含回調方法封裝的SubscriptionMethod類,在裏面保存了咱們反射執行方法的各類參數等信息;
Map<Object, List<Class<?>>> typesBySubscriber: key:訂閱者的實例對象,value:訂閱者中所監聽的全部的事件類型,一個訂閱者能夠有多個消息處理函數,所以會有多個事件類型;這個map還能夠在取消訂閱/註冊的時候快速查找到相應的事件類型,進行快速刪除subscriptionsByEventType中訂閱者的註冊信息;
Map<Class<?>, Object> stickyEvents:key:粘性事件的事件類型,value:粘性事件的事件類型的實例;因爲粘性事件的數據是存儲在內存中,當被訂閱者發送粘性事件時,首先會向stickyEvents 集合中添加數據,當訂閱者進行粘性事件訂閱/註冊時,就會從stickyEvents取出粘性事件的事件實例進行分發,保證了當我註冊/訂閱粘性事件時,也能夠接收到之前被訂閱者發送的事件信息;
在EventBus對象初始化過程當中,也會對EventBus內部的其餘對象進行建立:
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; }