EventBus主要流程分析
EventBus原理分析概要:
通过@Subscribe注解标记订阅事件(@Subscribe是一个运行时注解,参数包含订阅方法接收事件所在的线程、优先级、是否为粘性事件)。事件订阅的整个流程可以分为两块:注册注销和发射事件处理事件。
本篇文章是分析EventBus主体功能流程,像线程切换、优先级、粘性事件本文不做介绍。
EventBus的使用流程是:注册、发送事件、接收事件、反注册
以下介绍几个重点对象:
- 订阅方法对象 SubscriberMethod:包含Method对象、订阅事件类型、订阅优先级、订阅是否粘性、接收订阅事件的线程
public class SubscriberMethod {
final Method method;
final ThreadMode threadMode;
final Class<?> eventType;
final int priority;
final boolean sticky;
/** Used for efficient comparison */
String methodString;
-
订阅的事件对象 Subscription:映射订阅类class对象和订阅方法对象
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
final class Subscription {
final Object subscriber;
final SubscriberMethod subscriberMethod;
-
订阅类对象和订阅方法集合对象的映射:作用是用来缓存类中的订阅方法集合对象,以免每次当一个类去注册订阅的时候都要遍历所有的方法,直接从缓存中取,提高性能。
Map<Class订阅类对象,订阅方法集合对象> METHOD_CACHE = new HashMap<>();
private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();
-
订阅类对象和订阅事件类型对象的映射
Map<Class订阅类对象,EventType订阅事件类型对象> typesBySubscriber = new HashMap<>();
// 订阅类对象和订阅事件类型对象的映射
Map<Object, List<Class<?>>> typesBySubscriber = new HashMap<>();
-
事件类型对象和订阅事件对象集合的映射
Map<EventType事件类型对象,CopyOnWriteArrayList<Subscription>订阅事件对象集合> subscriptionsByEventType = new HashMap<>();
// 事件类型对象和订阅事件对象集合的映射
Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType = new HashMap<>();
1. 注册订阅
怎么注册:
EventBus.getDefault().register(this);
注册流程的核心方法:
public void register(Object subscriber) {
// 得到当前要注册类的Class对象
Class<?> subscriberClass = subscriber.getClass();
// 根据Class查找当前类中订阅了事件的方法集合,即使用了Subscribe注解、有public修饰符、一个参数的方法
// SubscriberMethod类主要封装了符合条件方法的相关信息:
// Method对象、线程模式、事件类型、优先级、是否是粘性事等
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
// 循环遍历订阅了事件的方法集合,以完成注册
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// METHOD_CACHE是一个ConcurrentHashMap,直接保存了subscriberClass和对应SubscriberMethod的集合,以提高注册效率,赋值重复查找。
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// 由于使用了默认的EventBusBuilder,则ignoreGeneratedIndex属性默认为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 {
// 保存查找到的订阅事件的方法
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
// 初始状态下findState.clazz就是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.clazz为subscriberClass的父类Class,即需要遍历父类
findState.moveToSuperclass();
}
// 查找到的方法保存在了FindState实例的subscriberMethods集合中。
// 使用subscriberMethods构建一个新的List<SubscriberMethod>
// 释放掉findState
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();
// 如果是public类型,但非abstract、static等
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 获得当前方法所有参数的类型
Class<?>[] parameterTypes = method.getParameterTypes();
// 如果当前方法只有一个参数
if (parameterTypes.length == 1) {
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
// 如果当前方法使用了Subscribe注解
if (subscribeAnnotation != null) {
// 得到该参数的类型
Class<?> eventType = parameterTypes[0];
// checkAdd()方法用来判断FindState的anyMethodByEventType map是否已经添加过以当前eventType为key的键值对,没添加过则返回true
if (findState.checkAdd(method, eventType)) {
// 得到Subscribe注解的threadMode属性值,即线程模式
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 创建一个SubscriberMethod对象,并添加到subscriberMethods集合
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");
}
}
}
// 真正开始注册
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 得到当前订阅了事件的方法的参数类型
Class<?> eventType = subscriberMethod.eventType;
// Subscription类保存了要注册的类对象以及当前的subscriberMethod
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// subscriptionsByEventType是一个HashMap,保存了以eventType为key,Subscription对象集合为value的键值对
// 先查找subscriptionsByEventType是否存在以当前eventType为key的值
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 如果不存在,则创建一个subscriptions,并保存到subscriptionsByEventType
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);
}
}
// 添加上边创建的newSubscription对象到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;
}
}
// typesBySubscribere也是一个HashMap,保存了以当前要注册类的对象为key,注册类中订阅事件的方法的参数类型的集合为value的键值对
// 查找是否存在对应的参数类型集合
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
// 不存在则创建一个subscribedEvents,并保存到typesBySubscriber
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
// 保存当前订阅了事件的方法的参数类型
subscribedEvents.add(eventType);
// 粘性事件相关的,后边具体分析
if (subscriberMethod.sticky) {
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 {
Object stickyEvent = stickyEvents.get(eventType);
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
注册的核心流程分为查找和缓存。
第一步:查找,根据当前订阅类对象遍历所有的方法,首先第一道筛选只有一个参数的方法,第二道根据有无注解和注解类型是不是@Subscribe过滤出注册Event事件的方法进行缓存。第二步:缓存两个映射,1. 当前类对象和事件参数类型集合对象映射;2. 事件参数类型和注册事件参数的方法集合对象映射。
subscribe() 方法主要是得到了subscriptionsByEventType、typesBySubscriber两个 HashMap。我们在发送事件的时候要用到subscriptionsByEventType,完成事件的处理。当取消 EventBus 注册的时候要用到typesBySubscriber、subscriptionsByEventType,完成相关资源的释放。
2. 取消注册
EventBus 如何取消注册:
EventBus.getDefault().unregister(this);
核心方法:
public synchronized void unregister(Object subscriber) {
// 得到当前注册类对象 对应的 订阅事件方法的参数类型 的集合
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
// 遍历参数类型集合,释放之前缓存的当前类中的Subscription
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
// 删除以subscriber为key的键值对
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
// 得到当前参数类型对应的Subscription集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
// 遍历Subscription集合
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
// 如果当前subscription对象对应的注册类对象 和 要取消注册的注册类对象相同,则删除当前subscription对象
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
取消注册,就是根据当前要取消的类对象为Key从缓存映射 typesBySubscriber 中拿到所有的订阅事件类型参数对象集合,然后遍历用每一个订阅事件类型参数对象为Key从缓存映射 subscriptionsByEventType 中拿到事件订阅方法集合,遍历,如果事件订阅方法对象中的订阅类对象subscriber与当前要取消注册的sbscriber对象相同的话,则从订阅缓存中移除各个订阅对象,完成取消注册。
3.发送事件和处理事件
怎么发送事件:
EventBus.getDefault().post("Hello World!");
重点代码:
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 获取事件类型对应的Subscription集合
subscriptions = subscriptionsByEventType.get(eventClass);
}
// 如果已订阅了对应类型的事件
if (subscriptions != null && !subscriptions.isEmpty()) {
for (Subscription subscription : subscriptions) {
// 记录事件
postingState.event = event;
// 记录对应的subscription
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;
}
发送事件使用到映射 subscriptionsByEventType ,根据事件类型从 subscriptionsByEventType 拿到订阅的事件方法对象集合,然后遍历拿到订阅的方法对象通过反射执行订阅方法
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);
}
}