前面已經(jīng)說(shuō)了EventBus的基本用法,下面我們一步步的看下Eventbus中到底做了些什么,為什么使用Index就讓性能得到了提升。
注冊(cè)
1、獲取EventBus實(shí)例
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
通過(guò)這種雙重校驗(yàn)鎖的方式獲取單例,當(dāng)然獲取實(shí)例的方式還有其他方法,但是強(qiáng)烈建議你使用這種方式,否則你會(huì)遇到一項(xiàng)不到的事情。
2、注冊(cè)
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
// 查找注冊(cè)類中監(jiān)聽(tīng)的方法(通過(guò)注解或者索引)
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
// 注冊(cè)方法
subscribe(subscriber, subscriberMethod);
}
}
}
在注冊(cè)時(shí),首先會(huì)通過(guò)SubscriberMethodFiner屬性的findSubscriberMethods方法找到訂閱者所有的訂閱方法;然后遍歷訂閱方法,對(duì)統(tǒng)一訂閱統(tǒng)一類型消息的方法在一個(gè)集合里;訂閱類和訂閱方法放在map中做一個(gè)映射,方便后邊的反注冊(cè)。
3、SubscriberMethodFinder查找方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// 默認(rèn)為false,只有指定ignoreGeneratedIndex=true才會(huì)為true
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 {
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
SubscriberMethodFinder的findSubscriberMethods首先會(huì)通過(guò)緩存找到,找到了就返回,找不到就繼續(xù)找,查找方式有兩種反射和索引,主要通過(guò)ignoreGeneratedIndex,這個(gè)屬性默認(rèn)為false,首先進(jìn)行索引找到,索引未找到時(shí)才會(huì)啟動(dòng)反射查找
4、反射查找
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
findUsingReflectionInSingleClass(findState);
findState.moveToSuperclass();
}
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();
} 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 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");
}
}
}
反射遍歷每一個(gè)方法,然后通過(guò)注解和參數(shù)進(jìn)行校驗(yàn),放在FindState的subscriberMethods集合里面
5、使用索引查找
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != 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 {
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
重點(diǎn)是在findUsingInfo里面調(diào)用了getSubscriberInfo方法,這個(gè)方法遍歷調(diào)用索引的getSubscriberInfo方法,返回空則進(jìn)行下一個(gè),不為空直接返回結(jié)果。如果查找了所有的索引都沒(méi)有那么會(huì)使用findUsingReflectionInSingleClass使用反射查找,那遍歷的索引是在EventBusBuilder
的addIndex方法中加入的。
6、找到方法之后,還要進(jìn)行注冊(cè),這里一步是方便后面的發(fā)布消息以及取消注冊(cè)的操作
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
// 方便發(fā)送消息的操作
subscriptionsByEventType.put(eventType, subscriptions);
}
// 省略部分代碼
// 優(yōu)先級(jí)
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;
}
}
// 方便后面的反注冊(cè)操作
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
}
這里主要有兩個(gè)Map:subscriptionsByEventType和typesBySubscriber,消息函數(shù)參數(shù)->所有的訂閱方法,訂閱類->訂閱方法。到此EventBus的注冊(cè)功能結(jié)結(jié)束了,我們來(lái)看下他的時(shí)序圖
消息發(fā)送
1、通過(guò)調(diào)用EventBus的post方法即可完成消息的發(fā)送,在post方法中調(diào)用了postSingleEvent方法,postSingleEvent方法會(huì)繼續(xù)調(diào)用postSingleEventForEventType方法
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;
}
postSingleEventForEventType方法通過(guò)subscriptionsByEventType獲取消息類型對(duì)應(yīng)的Subscription集合,Subscription封裝了實(shí)例和訂閱方法名,這樣我們就可以進(jìn)行調(diào)用了。
2、執(zhí)行訂閱方法,找到Subscription之后,就會(huì)遍歷執(zhí)行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);
}
}
在此方法中會(huì)根據(jù)Subscription的threadMode來(lái)執(zhí)行,我們最常用的就Main,我們看到如果當(dāng)前是主線程會(huì)直接執(zhí)行,如果不是主線程會(huì)使用mainThreadPoster,其實(shí)這是一個(gè)主進(jìn)程的Handler,這也是為什么我們可以在threadMode=main的訂閱方法中操作UI的原因
3、HandlerPoster的enqueue方法,發(fā)送消息
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");
}
}
}
}
首先這里先封裝成PendingPost,然后加入隊(duì)列,發(fā)送一個(gè)空的消息,為啥要這樣搞呢?可能是因?yàn)橹苯影l(fā)送一個(gè)消息過(guò)去,不方便傳遞Subscription和Event吧。
4、handleMessage
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
這里回去取出消息,然后再調(diào)用EvenBus的invokeSubscriber方法。這里應(yīng)該是真正執(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);
}
}
OK,在這里執(zhí)行了invoke方法,訂閱方法被調(diào)用了。
EventBus反注冊(cè)
public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
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());
}
}
包括一下幾個(gè)步驟:
1、找到訂閱類訂閱的消息類型
2、遍歷消息類型,找到消息類型對(duì)應(yīng)的所有的訂閱方法
3、遍歷所有訂閱方法,如果實(shí)例等于這個(gè)反注冊(cè)的訂閱類的進(jìn)行去除操作(unsubscribeByEventType方法)
4、去除訂閱類到訂閱消息類型的映射
在使用EventBus過(guò)程中,一定要取消訂閱,否則會(huì)導(dǎo)致內(nèi)存泄漏。