这篇文章,主要分析一下checkAdd这个方法:
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}这个checkAdd方法,主要判断 subscriberMethod订阅好的方法,是否可以添加到 subscriberMethods订阅方法的集合当中。
接下来我们来看下checkAdd这个方法:
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.
// 返回的是之前的value,也就是之前的那个方法
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;
} else {
if (existing instanceof Method) {
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);
}
}但是 大家需要注意的一点是,在EventBus当中,它有一个特点,它一个订阅者,包括这个订阅者所有的父类和子类,它不会有多个方法,相同的全部去接收同一个事件。
但是可能会出现这样一种情况,什么情况呢 ?
子类去订阅该事件,同时 父类也去订阅该事件,当这样一种情况出现,
我们的在EventBus是如何来判断的呢 ?
它会走到 checkAddWithMethodSignature(method, eventType) 方法这里。
private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());
String methodKey = methodKeyBuilder.toString();
Class<?> methodClass = method.getDeclaringClass();
// 本方法为key,订阅好的类Class对象为value
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
// 如果Class对象不存在,或者这个值是我们method父类的话,这个时候就返回true
if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
// Only add if not already found in a sub class
return true;
} else {
// Revert the put, old class is further down the class hierarchy
/**
* 这个中心思想就是,我们不要出现一个订阅者,有多个相同方法,订阅同一个事件,
* 如果有的话,我们就把以前的Class放到HashMap当中去覆盖。
*
*/
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}
}
本文深入剖析了EventBus中checkAdd方法的工作原理及其在处理订阅者方法时的逻辑,特别是如何避免同一事件被多个相同的方法订阅。
545

被折叠的 条评论
为什么被折叠?



