2.2Subscriber向Eventbus注册自己
2.2.1 register方法
接下来看register方法代码:
public void register(Object subscriber) {
//获得订阅者的class对象
Class<?> subscriberClass = subscriber.getClass();
//根据订阅者对象的Class对象查找当前订阅者的订阅方法(所有事件响应函数)
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
//循环每个事件响应函数
subscribe(subscriber, subscriberMethod);
}
}
}
subscriberClass就是订阅者所属的Class,如MainActivity.class,之后利用subscriberMethodFinder查找subscriberClass中的所有事件响应函数,先了解下SubscriberMethod类:
public class SubscriberMethod {
final Method method;//方法
final ThreadMode threadMode;//执行线程
final Class<?> eventType;//接收的事件类型
final int priority;//优先级
final boolean sticky;
....
}
SubscriberMethod类中封装了某个事件响应函数的信息,包括:Method对象、执行环境、接收的事件类型、优先级和是否是sticky事件。
2.2.2 SubscriberMethodFinder的实现
SubscriberMethodFinder类用来查找和缓存订阅者中的订阅方法(事件响应函数)的信息类。
SubscriberMethodFinder .findSubscriberMethods()方法如下:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//先从METHOD_CACHE查看是否有缓存,key:订阅类的class对象,value:保存订阅类中所有订阅方法(事件响应函数)。
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//是否忽略注解器生成的索引类(MyEventBusIndex)
if (ignoreGeneratedIndex) {
//在运行时利用反射来获得订阅类中的所有订阅方法(事件响应函数)
subscriberMethods = findUsingReflection(subscriberClass);
} else {
//在编译时从注解器生成的索引类(MyEventBusIndex)中获得所有订阅方法(事件响应函数)
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
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
该方法首先从缓存中获取订阅类的订阅方法(事件响应函数)信息,如果没有则通过以下两种方式来获取:
1、在编译时,通过EventBusAnnotationProcessor(注解处理器)结合@Subscriber所注解方法生成的MyEventBusIndex类中获取。
有关于这种方式请到这:EventBus3.0新特性之Subscriber Index
2、在运行时,通过反射来获取订阅类中订阅方法(事件响应函数)的信息
2.2.2 使用反射获取订阅信息
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
SubscriberMethodFinder.FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//真正的通过反射来获得订阅方法信息逻辑
findUsingReflectionInSingleClass(findState);
//查找父类的订阅方法
findState.moveToSuperclass();
}
// 获取findState中的subscriberMethods(也就是订阅方法List)并返回
return getMethodsAndRelease(findState);
}
FindState其实就是一个封装了订阅相关信息的类,最终是通过findUsingReflectionInSingleClass()来具体获得相关订阅方法的信息的:
private void findUsingReflectionInSingleClass(SubscriberMethodFinder.FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
//这种方式获取Method类型数组比getMethods方法更快,特别是当在订阅者是胖类比如像activity时。
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
//如果getDeclaredMethods方式获取Method类型数组时,抛出异常则改为使用getMethods方式获取到订阅类中的所有方法
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
int modifiers = method.getModifiers();
//选择是public和非static,非abstract,非bridge,非synthetic的方法
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];
//校验是否添加该订阅方法
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对象,最后再通过getMethodsAndRelease()解析得到List<SubscriberMethod>。
至此,通过反射获取订阅方法信息这种方式已经分析完了。
2.2.3 使用EventBusAnnotationProcessor获取订阅信息
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
SubscriberMethodFinder.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 {
//如果发现获取不到subscriberInfo的话,就还是要使用反射来获取。
findUsingReflectionInSingleClass(findState);
}
//会切换findState.clazz对象为父类的Class对象
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
查看getSubscriberInfo():
private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
subscriberInfoIndexes是属于SubscriberInfoIndex类型数组。SubscriberInfoIndex是一个接口,MyEventBusIndex实现了这个接口。
subscriberInfoIndexes是在执行addIndex方法被初始化并把MyEventBusIndex对象添加到此集合中。
EventBus eventBus = EventBus.builder().addIndex(new MyEventBusIndex());
/** Adds an index generated by EventBus' annotation preprocessor. */
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if(subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
}
MyEventBusIndex起作用是在SubscriberMethodFinder的getSubscriberInfo()中,以findState.clazz(订阅者的class对象)为key,在MyEventBusIndex.SUBSCRIBER_INDEX中查找,如果查找到了则直接返回。
至此,通过索引类获取订阅方法信息这种方式已经分析完了。
2.2.3 subscribe
回到2.2.1 register方法,在获取subscriberMethods之后,就是遍历各订阅方法,并执行subscribe方法。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//获取订阅方法(事件响应函数)的事件类型
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//从subscriptionsByEventType里检查是否已经添加过该Subscription,如果添加过就抛出异常
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
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++) {
//根据优先级priority将当前订阅者信息插入到订阅者队列中
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
//获取订阅者所有订阅的事件类型
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
//把订阅者对象作为key,对应订阅的事件类型集合作为value,保存到typesBySubscriber中。
typesBySubscriber.put(subscriber, subscribedEvents);
}
//将该事件类型添加到typesBySubscriber中
subscribedEvents.add(eventType);
//如果接收sticky事件,立即分发sticky事件
if (subscriberMethod.sticky) {
//eventInheritance 表示是否分发订阅了事件的父类的事件响应函数
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);
}
}
}
在此方法中,主要完成以下事情:
- 事件与订阅类中订阅方法进行绑定。
- 订阅对象与所有订阅的事件类型进行绑定
- 对sticky事件进行相关处理
至此,完成对[2.2Subscriber向Eventbus注册自己]过程的源码分析。
Subscriber向Eventbus注册自己的执行流程图:
register方法执行流程图
网友评论