/** Posts the given event to the event bus. */
public void post(Object event) {
// PostingThreadState : 发送事件的一个线程状态的封装类 duanran
// currentPostingThreadState 作用:线程独有的,不会让其他线程共享当前线程数据
PostingThreadState postingState = currentPostingThreadState.get();
// 获取到事件的队列
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
// 判断是否在进行发送
if (!postingState.isPosting) {
postingState.isMainThread = isMainThread();
// 表示事件已正在分发了,其他事件先阻塞在这里,等会再走
postingState.isPosting = true;
// 如果标志位取消的话
if (postingState.canceled) {
throw new EventBusException("Internal error. Abort state was not reset");
}
try {
// 循环,直到整个队列都为空
while (!eventQueue.isEmpty()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
/** For ThreadLocal, much faster to set (and get multiple values). */
final static class PostingThreadState {
// 事件队列集合
final List<Object> eventQueue = new ArrayList<>();
// 是否正在发送事件的标志位
boolean isPosting;
// 是否在主线程判断的标志位
boolean isMainThread;
// 将订阅者和订阅方法,封装起来的封装类
Subscription subscription;
// 事件
Object event;
// 取消标志位
boolean canceled;
}
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
// 判断 是否查看 这个事件有关的 所有的继承关系
if (eventInheritance) {
// 通过 lookupAllEventTypes 查找到所有继承关系的事件类型
List<Class<?>> 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 {
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) {
// NoSubscriberEvent 表示没有订阅者订阅该事件
post(new NoSubscriberEvent(this, event));
}
}
}