EventBus(五post分析)
public void post(Object event) {
// 注意此刻用的currentPostingThreadState时ThreadLocal,当前线程的独有的信息
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;
}
}
}
// 当前线程的一些重要信息和标志的封装类
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) {
// 找到所有订阅事件的事件类型(包括继承关系)
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) {
post(new NoSubscriberEvent(this, event));
}
}
}
总结:总体流程比较简单,将当前事件添加到队列,当中重置一些标志位以及判断一些标志为,轮询所有的事件,调用postSingleEventForEventType,返回订阅是否找到的标志位,进行处理。