case MAIN:
//case:主线程
if (isMainThread) {
invokeSubscriber(subscription, event);
}
//case:非主线程
else {
mainThreadPoster.enqueue(subscription, event);
}
break;
public class HandlerPoster extends Handler implements Poster
public void enqueue(Subscription subscription, Object event) {
//创建PendingPost对象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
//加入队列
queue.enqueue(pendingPost);
//如果不在处理中,那么发送一个Message激活激活处理流程
if (!handlerActive) {
handlerActive = true;
//发送一个Message
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
//从队列中取PengingPost
PendingPost pendingPost = queue.poll();
//双重检查,由于enqueue存在并发问题
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
//没有要处理的事件了,置标志位为false,表示不在处理中了
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
//反射调用订阅方法
eventBus.invokeSubscriber(pendingPost);
//记录进入while循环的事件
long timeInMethod = SystemClock.uptimeMillis() - started;
//处理超时,默认10ms,跳出,但是处理中激活标志仍为true,因为又发了一条Message
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
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;