EventBus.getDefault().register(this);
public void register(Object subscriber) {
Class subscriberClass = subscriber.getClass();
// 获取类里面的方法集合
List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
List findSubscriberMethods(Class subscriberClass) {
List subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
// 从缓存获取,如果已经已经订阅过,直接返回
return subscriberMethods;
}
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 findUsingInfo(Class subscriberClass) {
// 获取一个 FindState 用来存储订阅者信息,里面使用 FIND_STATE_POOL 池的缓存 FindState
FindState findState = prepareFindState();
// 对FindState 初始化
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 设置订阅者信息,用户将注册的方法提前保存在 SubscriberInfo 中
// 简单点讲,自己麻利滴 将这个类及父类需要响应的方法列表列出来,我就不一一去找了,
// 通过EventBusBuilder addIndex设置,不过基本上很少用到
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);
}
findUsingReflectionInSingleClass 通过反射获取方法,获取Eventbus 的响应方法后封装成一个 SubscriberMethod 并添加进 findState.subscriberMethods 集合中。
SubscriberMethod 参数:method 目标方法,eventType 事件类型,threadMode 响应的线程, priority 优先级,sticky 是否是粘性事件
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
// 只返回当前 class 的方法
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();
//订阅的方法 must be public, non-static, and non-abstract
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 参数集合
Class[] parameterTypes = method.getParameterTypes();
// 参数至少要一个 就是我们的 定义的类 如 FirstBean
if (parameterTypes.length == 1) {
// 再获取自定义注解
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
// 事件类型 如 FirstBean
Class eventType = parameterTypes[0];
// 对方法检查方法签名
if (findState.checkAdd(method, eventType)) {
// 获取 ThreadMode
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 封装成 SubscriberMethod 保存
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 List getMethodsAndRelease(FindState findState) {
// 之前保存的所有 订阅的方法
List subscriberMethods = new ArrayList<>(findState.subscriberMethods);
findState.recycle();
synchronized (FIND_STATE_POOL) {
// 放进 FIND_STATE_POOL 缓存里,但是只能缓存4个
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
public void register(Object subscriber) {
Class subscriberClass = subscriber.getClass();
// 获取类里面的方法集合
List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 获取响应方法的 事件类型
Class eventType = subscriberMethod.eventType;
// 将订阅者(响应的类) 和 每一个响应方法 封装成 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 根据事件类型 先获取响应这个事件的集合 集合元素就是上面封装的 Subscription
CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
// 同一事件类型的 读写集合集合 key 事件类型;value 封装的 Subscription
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) {
// 根据优先级 将封装 Subscription 对象 放进集合
subscriptions.add(i, newSubscription);
break;
}
}
... 省略后半 ...
}
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
.. 省略前段...
List> subscribedEvents = typesBySubscriber.get(subscriber);
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).
Set, Object>> entries = stickyEvents.entrySet();
for (Map.Entry, 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);
}
}
}
public void post(Object event) {
// ThreadLocal 线程本地变量,每次get 获取当前线程 设置的 PostingThreadState对象
PostingThreadState postingState = currentPostingThreadState.get();
// PostingThreadState 对象中保存当前线程的执行队列
List
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class eventClass = event.getClass();
boolean subscriptionFound = false;
if (eventInheritance) {
// 根据事件类型 查找所有的响应类包括父类和子类接口
List> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class clazz = eventTypes.get(h);
// 具体响应事件
subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
}
} else {
// 默认 eventInheritance false,
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
// 没有订阅者 订阅此事件
if (!subscriptionFound) {
if (logNoSubscriberMessages) {
logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
}
if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
eventClass != SubscriberExceptionEvent.class) {
post(new NoSubscriberEvent(this, event));
}
}
}
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
CopyOnWriteArrayList 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;
}
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 MAIN_ORDERED:
if (mainThreadPoster != null) {// 在队列中有序执行
mainThreadPoster.enqueue(subscription, event);
} else {
// temporary: technically not correct as poster not decoupled from subscriber
invokeSubscriber(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);
}
}
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);
}
}
if (mainThreadPoster != null) {// 在队列中有序执行
mainThreadPoster.enqueue(subscription, event);
} else {
// temporary: technically not correct as poster not decoupled from subscriber
invokeSubscriber(subscription, event);
}
public synchronized void unregister(Object subscriber) {
List> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
// 从订阅集合中移除
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 subscriptions = subscriptionsByEventType.get(eventType);
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;
subscriptions.remove(i);
i--;
size--;
}
}
}
}