看了好幾次EventBus源碼了,這次總算基本上搞清楚了,簡單來說就是調用 EventBus.getDefault().register(this),將訂閱者類(如下MainActivity)中所有訂閱方法(如下onMessageEvent方法)存下來,然后某個對象在調用EventBus.getDefault().post(new MsgEvent())時,實際上是通過反射調用之前存好的訂閱方法,本文分為以下幾個部分:注冊、銷毀、發送事件來解讀EventBus。
基本用法
我把基本用法的代碼貼出來,方便我們查看,并根據代碼來理解其邏輯:
消息事件:
public class MsgEvent {
}
應用類:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
EventBus.getDefault().post(new MsgEvent());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MsgEvent event) {
Log.d("tag","******just a event****");
};
}
我們主要從注冊事件EventBus.getDefault().register(this);發送事件EventBus.getDefault().post(new MsgEvent()); 取消注冊事件EventBus.getDefault().unregister(this);來開始分析EventBus。
重要的數據結構
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
private final Map<Class<?>, Object> stickyEvents;
final class Subscription {
final Object subscriber;
final SubscriberMethod subscriberMethod;
volatile boolean active;
Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
this.subscriber = subscriber;
this.subscriberMethod = subscriberMethod;
active = true;
}
...此處省略
}
subscriptionsByEventType:以event(即事件類)為key,以訂閱列表(Subscription)為value,事件發送之后,在這里尋找訂閱者,而Subscription又是一個CopyOnWriteArrayList,這是一個線程安全的容器。你們看會好奇,Subscription到底是什么,其實看下去就會了解的,現在先提前說下:Subscription是一個封裝類,封裝了訂閱者、訂閱方法這兩個類。
typesBySubscriber:以訂閱者類為key,以event事件類為value,在進行register或unregister操作的時候,會操作這個map。
stickyEvents:保存的是粘性事件,粘性事件上一篇文章有詳細描述。
回到EventBus的構造方法,接下來實例化了三個Poster,分別是mainThreadPoster、backgroundPoster、asyncPoster等,這三個Poster是用來處理粘性事件的,我們下面會展開講述。接著,就是對builder的一系列賦值了,這里使用了建造者模式。
Subscription:以訂閱者為key(類比上面的MainActivity),以訂閱者中方法(類比上面的onMessageEvent方法)為value。
注冊事件
要想注冊成為訂閱者,必須在一個類中調用如下:
EventBus.getDefault().register(this);
那么,我們看一下getDefault()的源碼是怎樣的,EventBus#getDefault():
getDefault()
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
可以看出,這里使用了單例模式,而且是雙重校驗的單例,確保在不同線程中也只存在一個EvenBus的實例。
register
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
先獲取了訂閱者類的class,接著交給SubscriberMethodFinder.findSubscriberMethods()處理,返回結果保存在List<SubscriberMethod>(即上面的onMessageEvent)中,由此可推測通過上面的方法把訂閱方法找出來了,并保存在集合中。
為了方便讀者理解,具體findSubscriberMethods()分析在最后一節。
在找到訂閱者中所有的方法集合subscriberMethods后,將執行subscribe(subscriber, subscriberMethod),生成subscription,將所有subscription都添加到subscriptionsByEventType變量中,獲取subscriberMethod的類型,并賦值給typesBySubscriber。
subscribe
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
//將subscriber和subscriberMethod封裝成 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//根據事件類型獲取特定的 Subscription
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//如果為null,說明該subscriber尚未注冊該事件
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//如果不為null,并且包含了這個subscription 那么說明該subscriber已經注冊了該事件,拋出異常
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
//根據優先級來設置放進subscriptions的位置,優先級高的會先被通知
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;
}
}
//根據subscriber(訂閱者)來獲取它的所有訂閱事件
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
//把訂閱者、事件放進typesBySubscriber這個Map中
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
//下面是對粘性事件的處理
if (subscriberMethod.sticky) {
//從EventBusBuilder可知,eventInheritance默認為true.
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();
if (eventType.isAssignableFrom(candidateEventType)) {
Object stickyEvent = entry.getValue();
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
} else {
//根據eventType,從stickyEvents列表中獲取特定的事件
Object stickyEvent = stickyEvents.get(eventType);
//分發事件
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
到目前為止,注冊流程基本分析完畢。
發送事件
EventBus.getDefault().post(new MessageEvent());`
post
public void post(Object event) {
//1、 獲取一個postingState
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()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
首先是獲取一個PostingThreadState,那么PostingThreadState是什么呢?我們來看看它的類結構:
PostingThreadState
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
可以看出,該PostingThreadState主要是封裝了當前線程的信息,以及訂閱者、訂閱事件等。那么怎么得到這個PostingThreadState呢?讓我們回到post()方法,看①號代碼,這里通過currentPostingThreadState.get()來獲取PostingThreadState。那么currentPostingThreadState又是什么呢?
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
原來 currentPostingThreadState是一個ThreadLocal,而ThreadLocal是每個線程獨享的,其數據別的線程是不能訪問的,因此是線程安全的。我們再次回到Post()方法,繼續往下走,是一個while循環,這里不斷地從隊列中取出事件,并且分發出去,調用的是EventBus#postSingleEvent方法。
postSingleEvent
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//該eventInheritance上面有提到,默認為true,即EventBus會考慮事件的繼承樹
//如果事件繼承自父類,那么父類也會作為事件被發送
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);
}
//如果沒找到訂閱該事件的訂閱者
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));
}
}
}
postSingleEventForEventType
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
//從subscriptionsByEventType獲取響應的subscriptions
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;
}
//...
}
return true;
}
return false;
}
接著,進一步調用了EventBus#postToSubscription,可以發現,這里把訂閱列表作為參數傳遞了進去,顯然,訂閱列表內部保存了訂閱者以及訂閱方法,那么可以猜測,這里應該是通過反射的方式來調用訂閱方法。具體怎樣的話,我們看源碼。
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);
}
}
首先獲取threadMode,即訂閱方法運行的線程,如果是POSTING,那么直接調用invokeSubscriber()方法即可,如果是MAIN,則要判斷當前線程(post事件的線程)是否是MAIN線程,如果是也是直接調用invokeSubscriber()方法,否則會交給mainThreadPoster來處理,其他情況相類似。
invokeSubscriber
主要利用反射的方式來調用訂閱方法,這樣就實現了事件發送給訂閱者,訂閱者調用訂閱方法這一過程。如下所示:
void invokeSubscriber(Subscription subscription, Object event) {
try {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
}
//...
}
HandlerPoster
我們首先看mainThreadPoster,它的類型是HandlerPoster繼承自Handler:
final class HandlerPoster extends Handler {
//PendingPostQueue隊列,待發送的post隊列
private final PendingPostQueue queue;
//規定最大的運行時間,因為運行在主線程,不能阻塞主線程
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
//省略...
}
可以看到,該handler內部有一個PendingPostQueue,這是一個隊列,保存了PendingPost,即待發送的post,該PendingPost封裝了event和subscription,方便在線程中進行信息的交互。在postToSubscription方法中,當前線程如果不是主線程的時候,會調用HandlerPoster#enqueue方法:
void enqueue(Subscription subscription, Object event) {
//將subscription和event打包成一個PendingPost
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");
}
}
}
}
首先會從PendingPostPool中獲取一個可用的PendingPost,接著把該PendingPost放進PendingPostQueue,發送消息,那么由于該HandlerPoster在初始化的時候獲取了UI線程的Looper,所以它的handleMessage()方法運行在UI線程:
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
//不斷從隊列中取出pendingPost
while (true) {
//省略...
eventBus.invokeSubscriber(pendingPost);
//..
}
} finally {
handlerActive = rescheduled;
}
}
里面調用到了EventBus#invokeSubscriber方法,在這個方法里面,將PendingPost解包,進行正常的事件分發,這上面都說過了,就不展開說了。
BackgroundPoster
BackgroundPoster繼承自Runnable,與HandlerPoster相似的,它內部都有PendingPostQueue這個隊列,當調用到它的enqueue的時候,會將subscription和event打包成PendingPost:
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
//如果后臺線程還未運行,則先運行
if (!executorRunning) {
executorRunning = true;
//會調用run()方法
eventBus.getExecutorService().execute(this);
}
}
}
該方法通過Executor來運行run()方法,run()方法內部也是調用到了EventBus#invokeSubscriber方法。
AsyncPoster
與BackgroundPoster類似,它也是一個Runnable,實現原理與BackgroundPoster大致相同,但有一個不同之處,就是它內部不用判斷之前是否已經有一條線程已經在運行了,它每次post事件都會使用新的一條線程。
注銷
與注冊相對應的是注銷,當訂閱者不再需要事件的時候,我們要注銷這個訂閱者,即調用以下代碼:
EventBus.getDefault().unregister(this);
那么我們來分析注銷流程是怎樣實現的,首先查看EventBus#unregister:
unregister
public synchronized void unregister(Object subscriber) {
//根據當前的訂閱者來獲取它所訂閱的所有事件
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍歷所有訂閱的事件
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//從typesBySubscriber中移除該訂閱者
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
上面調用了EventBus#unsubscribeByEventType,把訂閱者以及事件作為參數傳遞了進去,那么應該是解除兩者的聯系。
unsubscribeByEventType
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根據事件類型從subscriptionsByEventType中獲取相應的 subscriptions 集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
//遍歷所有的subscriptions,逐一移除
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
可以看到,上面兩個方法的邏輯是非常清楚的,都是從typesBySubscriber或subscriptionsByEventType移除相應與訂閱者有關的信息,注銷流程相對于注冊流程簡單了很多,其實注冊流程主要邏輯集中于怎樣找到訂閱方法上。
繼續分析findSubscriberMethods
findSubscriberMethods
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//首先從緩存中取出subscriberMethodss,如果有則直接返回該已取得的方法
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//從EventBusBuilder可知,ignoreGenerateIndex一般為false
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 {
//將獲取的subscriberMeyhods放入緩存中
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
findSubscriberMethods通過調用findUsingInfo來找到訂閱者中的所有方法集合。
findUsingInfo
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//準備一個FindState,該FindState保存了訂閱者類的信息
FindState findState = prepareFindState();
//對FindState初始化
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//獲得訂閱者的信息,一開始會返回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 {
//1 、到了這里
findUsingReflectionInSingleClass(findState);
}
//移動到父類繼續查找
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
上面用到了FindState這個內部類來保存訂閱者類的信息,我們看看它的內部結構:
FindState
static class FindState {
//訂閱方法的列表
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
//以event為key,以method為value
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
//以method的名字生成一個method為key,以訂閱者類為value
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
final StringBuilder methodKeyBuilder = new StringBuilder(128);
Class<?> subscriberClass;
Class<?> clazz;
boolean skipSuperClasses;
SubscriberInfo subscriberInfo;
//對FindState初始化
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
//省略...
}
可以看出,該內部類保存了訂閱者及其訂閱方法的信息,用Map一一對應進行保存,接著利用initForSubscriber進行初始化,這里subscriberInfo初始化為null,因此在SubscriberMethodFinder#findUsingInfo里面,會直接調用到①號代碼,即調用SubscriberMethodFinder#findUsingReflectionInSingleClass,這個方法非常重要!!!在這個方法內部,利用反射的方式,對訂閱者類進行掃描,找出訂閱方法,并用上面的Map進行保存,我們來看這個方法。
findUsingReflectionInSingleClass
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注解
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
//參數類型 即為 事件類型
Class<?> eventType = parameterTypes[0];
// 2 、調用checkAdd方法
if (findState.checkAdd(method, eventType)) {
//從注解中提取threadMode
ThreadMode threadMode = subscribeAnnotation.threadMode();
//新建一個SubscriberMethod對象,并添加到findState的subscriberMethods這個集合內
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
//如果開啟了嚴格驗證,同時當前方法又有@Subscribe注解,對不符合要求的方法會拋出異常
} 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");
}
}
}
雖然該方法比較長,但是邏輯非常清晰,逐一掃描訂閱者內所有的方法,并判斷訂閱者類中是否存在訂閱方法,如果符合要求,并且②號代碼調用FindState#checkAdd方法返回true的時候,才會把方法保存在findState的subscriberMethods內。而SubscriberMethod則是用于保存訂閱方法的一個類。
回到findUsingReflectionInSingleClass方法,當遍歷完當前類的所有方法后,會回到findUsingInfo方法,接著會執行最后一行代碼,即return getMethodsAndRelease(findState);
getMethodsAndRelease
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
//從findState獲取subscriberMethods,放進新的ArrayList
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
//把findState回收
findState.recycle();
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
通過該方法,把subscriberMethods返回。