EventBus注冊(cè)與反注冊(cè)流程源碼分析
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass(); //獲得訂閱者的class
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); // 查找訂閱者類(lèi)的所有訂閱方法
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
從上述代碼可以看出,注冊(cè)的大致流程為:
- 查找到訂閱者類(lèi)的所有訂閱方法
- 注冊(cè)訂閱信息
接下來(lái)我們來(lái)詳細(xì)分析通過(guò)SubscriberMethodFinder來(lái)查找訂閱方法的過(guò)程,在介紹之前我們先詳細(xì)看一下SubscriberMethod
public class SubscriberMethod {
final Method method; // 訂閱方法
final ThreadMode threadMode; // 標(biāo)識(shí)在哪個(gè)線(xiàn)程執(zhí)行,有POSTING,MAIN,BACKGROUND,ASYNC 四種模式
final Class<?> eventType; // 事件類(lèi)
final int priority; // 優(yōu)先級(jí)
final boolean sticky; // 是否是粘性事件
/** Used for efficient comparison */
String methodString;
....
}
SubscriberMethod 包含了訂閱方法相關(guān)的所有信息,接下來(lái)我們看SubscriberMethodFinder中是如何查找事件類(lèi)中的所有訂閱方法信息的
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass); //首先從METHOD_CACHE中讀取緩存下來(lái)的訂閱方法列表
if (subscriberMethods != null) {
return subscriberMethods;
}
// ignoreGeneratedIndex屬性表示是否忽略注解器生成的MyEventBusIndex。如何生成MyEventBusIndex類(lèi)以及他的使用,可以本文中apt部分的詳細(xì)說(shuō)明。ignoreGeneratedIndex的默認(rèn)值為false,可以通過(guò)EventBusBuilder來(lái)設(shè)置它的值
if (ignoreGeneratedIndex) {
// 利用反射來(lái)獲取訂閱類(lèi)中所有訂閱方法信息
subscriberMethods = findUsingReflection(subscriberClass);
} else {
// 從注解器生成的MyEventBusIndex類(lèi)中獲得訂閱類(lèi)的訂閱方法信息
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;
}
}
從上面代碼可以看出,SubscriberMethodFinder獲得訂閱方法信息列表的步驟為:
- 首先從訂閱方法緩存中獲取訂閱類(lèi)的訂閱方法,如果沒(méi)有則進(jìn)入步驟2
- 通過(guò)ignoreGeneratedIndex屬性判斷通過(guò)以下兩種方式中的一種來(lái)查找訂閱方法,這兩種方式為
-如果ignoreGeneratedIndex為FALSE,通過(guò)EventBusAnnotationProcessor(注解處理器)生成的MyEventBusIndex中獲取
-否則通過(guò)反射來(lái)獲取訂閱類(lèi)中訂閱方法信息
關(guān)于EventBusAnnotationProcessor注解處理器在本文中apt部分的介紹中有詳細(xì)闡述,此處不再贅述。我們?cè)敿?xì)解讀一下通過(guò)反射來(lái)獲取訂閱類(lèi)中訂閱方法信息列表的源代碼
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass); // 初始化FindState
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);// 尋找某個(gè)類(lèi)中的所有事件響應(yīng)方法
findState.moveToSuperclass(); //繼續(xù)尋找當(dāng)前類(lèi)父類(lèi)中注冊(cè)的事件響應(yīng)方法
}
return getMethodsAndRelease(findState);
}
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(); // 通過(guò)反射來(lái)獲取到訂閱者類(lèi)的所有方法
} 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();
// 找到所有聲明為 public 的方法
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes(); // 找到方法參數(shù)并且參數(shù)數(shù)量為1
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); // 得到注解,并將方法添加到訂閱信息中去
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
// 將訂閱方法信息加入到列表中
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} 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這個(gè)類(lèi),保存訂閱者和訂閱方法相關(guān)的信息,包括訂閱類(lèi)中所有訂閱的事件類(lèi)型和所有的訂閱方法等信息。
static class FindState {
final List<SubscriberMethod> subscriberMethods = new ArrayList<>(); // 訂閱方法信息列表
final Map<Class, Object> anyMethodByEventType = new HashMap<>(); //以事件類(lèi)型為key, 方法信息為value的集合
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>(); // 以methodkey為key,訂閱者類(lèi)為value的集合
final StringBuilder methodKeyBuilder = new StringBuilder(128); // 生成methodkey的stringbuilder
Class<?> subscriberClass; // 訂閱者類(lèi)
Class<?> clazz;
boolean skipSuperClasses; // 是否跳過(guò)父類(lèi)
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;
}
// checkAdd這部分的作用是檢測(cè)訂閱者中注冊(cè)的事件響應(yīng)方法是否可以合法的加入到訂閱方法信息中,分為兩層檢查
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.
//第一次檢查同一事件類(lèi)型下是否已有訂閱方法信息
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;//如果還未有訂閱方法監(jiān)聽(tīng)此事件,則可添加此訂閱方法信息
} else {
if (existing instanceof Method) {
// 檢測(cè)到同一事件類(lèi)型下已經(jīng)有訂閱事件響應(yīng)方法,則繼續(xù)進(jìn)行方法簽名的檢查
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);
}
}
// 使用訂閱方法簽名檢測(cè)是否可以加入訂閱方法信息列表
private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());//使用訂閱方法名以及訂閱事件類(lèi)型構(gòu)造methordKey
String methodKey = methodKeyBuilder.toString();
Class<?> methodClass = method.getDeclaringClass();
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass); //判斷是否存方法簽名相同的事件響應(yīng)方法,并比較相同方法簽名的訂閱方法所在類(lèi)的關(guān)系
if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
// Only add if not already found in a sub class
// 如果不存在同樣方法簽名的訂閱方法或者,之前保存的訂閱方法所在的類(lèi)為當(dāng)前將要添加的訂閱方法所在的類(lèi)的子類(lèi)(目前不存在此情況,因?yàn)橹粫?huì)從子類(lèi)向父類(lèi)查找),則可以合法添加此訂閱方法信息
return true;
} else {
// Revert the put, old class is further down the class hierarchy
//subscriberClassByMethodKey只保存父子繼承關(guān)系的最下層子類(lèi),目的是為了在子類(lèi)注冊(cè)監(jiān)聽(tīng)事件時(shí),如果父類(lèi)中有相同的事件響應(yīng)方法,應(yīng)該調(diào)用子類(lèi)的覆寫(xiě)方法。
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;
}
}
}
}
分析以上源碼,具體步驟如下:
- 通過(guò)反射得到當(dāng)前 class 的所有方法
- 過(guò)濾掉不是 public 和是 abstract、static、bridge、synthetic 的方法
- 找出所有參數(shù)只有一個(gè)的方法
- 找出被Subscribe注解的方法
- 把method 方法和 事件類(lèi)型eventtype添加到 findState 中
- 把 method 方法、事件類(lèi)型、threadMode、priority、sticky 封裝成 SubscriberMethod 對(duì)象,然后添加到 findState.subscriberMethods
以上為查找訂閱者類(lèi)中所有訂閱方法信息的詳細(xì)過(guò)程,查找完訂閱類(lèi)中所有訂閱方法信息后,遍歷所有訂閱方法信息,繼續(xù)進(jìn)行注冊(cè)的步驟
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType; // 獲取訂閱方法的事件類(lèi)
Subscription newSubscription = new Subscription(subscriber, subscriberMethod); // 創(chuàng)建訂閱類(lèi)
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); // 獲取訂閱了此事件類(lèi)的所有訂閱者信息列表,如果不存在則將其加入訂閱者信息列表,如果已經(jīng)存在此訂閱者信息則拋出已注冊(cè)的異常
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);
}
}
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;
}
} // 將訂閱者信息按照優(yōu)先級(jí)加入到訂閱者信息列表中
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); // 獲取此訂閱者實(shí)例訂閱的所有事件類(lèi)的列表
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType); // 將此事件類(lèi)加入 訂閱者事件類(lèi)列表中
// 判斷是否是粘性事件,對(duì)粘性事件立即進(jìn)行分發(fā)
if (subscriberMethod.sticky) {
if (eventInheritance) {
// 所有事件類(lèi)的子類(lèi)都要處理
// 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 {
// 如果當(dāng)前粘性事件集合中存在此事件類(lèi)對(duì)應(yīng)的粘性事件對(duì)象,則進(jìn)入事件分發(fā)流程
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
以上代碼的流程如下:
- 如果當(dāng)前訂閱信息沒(méi)有注冊(cè)過(guò),則按照優(yōu)先級(jí)加入到訂閱信息集合 subscriptionsByEventType(subscriptionsByEventType以事件類(lèi)為key,以訂閱信息列表為value的訂閱信息集合)。
- 將事件類(lèi)型加入到訂閱事件類(lèi)型集合 typesBySubscriber(typesBySubscriber 以訂閱者對(duì)象為key,以訂閱事件類(lèi)型為value的訂閱類(lèi)型信息集合)。
- 如果當(dāng)前訂閱的為粘性事件,則進(jìn)入事件分發(fā)的流程。
Map<Class<?>, Object> stickyEvents; 以事件類(lèi)為key,以事件對(duì)象為value的粘性事件集合
Subscription是訂閱信息類(lèi),包含訂閱者對(duì)象,訂閱方法,是否處于激活狀態(tài)等
final class Subscription {
final Object subscriber; // 訂閱者對(duì)象
final SubscriberMethod subscriberMethod; // 訂閱方法
/**
* Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
* {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
*/
volatile boolean active; // 是否處于激活狀態(tài)
Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
this.subscriber = subscriber;
this.subscriberMethod = subscriberMethod;
active = true;
}
@Override
public boolean equals(Object other) {
if (other instanceof Subscription) {
Subscription otherSubscription = (Subscription) other;
return subscriber == otherSubscription.subscriber
&& subscriberMethod.equals(otherSubscription.subscriberMethod);
} else {
return false;
}
}
@Override
public int hashCode() {
return subscriber.hashCode() + subscriberMethod.methodString.hashCode();
}
}
總結(jié)如上代碼流程,注冊(cè)的流程圖如下:
eventbus流程圖.png
反注冊(cè)流程源碼詳解
public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber); // 獲取訂閱對(duì)象的所有訂閱事件類(lèi)列表
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType); // 將訂閱者的訂閱信息移除
}
typesBySubscriber.remove(subscriber); // 將訂閱者從列表中移除
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType); // 獲取事件類(lèi)的所有訂閱信息列表,將訂閱信息從訂閱信息集合中移除,同時(shí)將訂閱信息中的active屬性置為FALSE
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false; // 將訂閱信息激活狀態(tài)置為FALSE
subscriptions.remove(i); // 將訂閱信息從集合中移除
i--;
size--;
}
}
}
}
反注冊(cè)的流程為:
- 將訂閱者的訂閱信息從訂閱信息集合中移除,同時(shí)將訂閱信息激活狀態(tài)置為FALSE
- 將訂閱者信息從訂閱者訂閱類(lèi)型集合中移除
總結(jié)如上代碼流程,注冊(cè)的流程圖如下:
Paste_Image.png