EventBus源码详解和设计分析(一)观察者订阅与注销
post
post()方法是EventBus发射普通消息的方法,方法如下:
public void post(Object event) {
//获取当前线程的发送状态
PostingThreadState postingState = currentPostingThreadState.get();
//获取事件队列并将该事件添加到队列
List
PostingThreadState类保存了订阅事件队列并维护订阅者的发射状态
final static class PostingThreadState {
final List
EventBus.currentPostingThreadState是一个ThreadLocal。post方法从PostingThreadState取出订阅方法表添加到eventQueue中。首先判断其发射状态,如果未正在发射,则设置其线程状态和发射状态,判断canceled属性,为true时抛出异常。最后调用postSingleEvent方法依次发射eventQueue中的订阅事件。postSingleEvent方法如下:
postSingleEvent()方法:发射单一事件
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class> eventClass = event.getClass();
boolean subscriptionFound = false;
//eventInheritance在builder中默认为true
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 {
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));
}
}
}
lookupAllEventTypes()方法查询所有订阅该事件的订阅者
private static List> lookupAllEventTypes(Class> eventClass) {
//查询时需锁住缓存表
synchronized (eventTypesCache) {
List> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class> clazz = eventClass;
//循环遍历父类
while (clazz != null) {
//添加本类及接口
eventTypes.add(clazz);
addInterfaces(eventTypes, clazz.getInterfaces());
//获取父类
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
}
lookupAllEventTypes方法从事件类型缓存中取出所有该事件的类型表,不为null则直返回;否则遍历该类型及其父类并添加到类型表中。
addInterfaces方法递归检查类型接口,将添加到eventTypes中的所有类型的接口类型也添加进来,如下:
static void addInterfaces(List> eventTypes, Class>[] interfaces) {
for (Class> interfaceClass : interfaces) {
if (!eventTypes.contains(interfaceClass)) {
eventTypes.add(interfaceClass);
addInterfaces(eventTypes, interfaceClass.getInterfaces());
}
}
}
综上,lookupAllEventTypes()方法获取了订阅事件的所有父类及其接口类型。
再回到postSingleEvent方法中,循环遍历获取到的类型列表eventTypes,调用postSingleEventForEventType方法:
postSingleEventForEventType():向所有订阅者发射事件并返回发射结果状态
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class> eventClass) {
CopyOnWriteArrayList subscriptions;
//锁住本方法,并获取所有关于该事件类型的订阅关系---subscriptions
synchronized (this) {
//获取该事件类型的订阅关系表
subscriptions = subscriptionsByEventType.get(eventClass);
}
//当subscriptions不为空时,遍历并调用postToSubscription()方法依次发射事件
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;
}
postSingleEventForEventType方法里,先拿到eventClass对应的Subscription表,为空则返回false。否则遍历该表,将取到的subscription和传参event合并到postingState中,调用postToSubscription()方法进发射。
postToSubscription()方法:分类发射事件
根据subscription.subscriberMethod.threadMode的类型,即订阅方法的运行线程,进行分类处理-----判断执行订阅方法的线程:
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调用
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);
}
}
POSTING:执行invokeSubscriber()方法直接反射调用;
MAIN:首先去判断当前是否在UI线程,如果是的话则直接反射调用,否则调用mainThreadPoster.enqueue(),把当前的方法加入到队列之中,然后通过HandlerPoster发送一个消息,并处理;
MAIN_ORDERED:判断mainThreadPoster不为null,则调用mainThreadPoster.enqueue(subscription, event);使用invokeSubscriber;
-
BACKGROUND:判断当前是否在UI线程,不是的话直接反射调用,如是则用backgroundPoster.enqueue()将方法加入到后台的一个队列,最后通过线程池去执行;
ASYNC:与BACKGROUND的逻辑类似,将任务加入到后台的一个队列,最终由Eventbus中的一个线程池去调用,这里的线程池与BACKGROUND逻辑中的线程池用的是同一个。
invokeSubscriber方法:反射调用订阅方法
使用method.invoke方法,通过反射调用subscriber中的event参数的订阅方法。
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);
}
}
/**
* 另一个重载方法,通过PendingPost封装类调用
*/
void invokeSubscriber(PendingPost pendingPost) {
Object event = pendingPost.event;
Subscription subscription = pendingPost.subscription;
//加入到缓存池
PendingPost.releasePendingPost(pendingPost);
if (subscription.active) {
invokeSubscriber(subscription, event);
}
}
invokeSubscriber是在当前线程直接执行订阅方法,其他的情况需要使用不同的Poster来在目标线程调用方法。
除了invokeSubscriber方法,其他的发射方法都是通过xxxxPoster.enqueue方法,我们接下来介绍EventBus的三种发射器和他们的enqueue方法。
关于另一个重载方法和PendingPost类,我会在下面介绍。
三种发送器
1. HandlerPoster:主线程发送器
EventBus(EventBusBuilder builder) {
...
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
}
MainThreadSupport getMainThreadSupport() {
if (mainThreadSupport != null) {
return mainThreadSupport;
} else if (Logger.AndroidLogger.isAndroidLogAvailable()) {
//获得主线程Looper
Object looperOrNull = getAndroidMainLooperOrNull();
return looperOrNull == null ? null :
new MainThreadSupport.AndroidHandlerMainThreadSupport((Looper) looperOrNull);
} else {
return null;
}
}
class AndroidHandlerMainThreadSupport implements MainThreadSupport {
private final Looper looper;
public AndroidHandlerMainThreadSupport(Looper looper) {
this.looper = looper;
}
@Override
public boolean isMainThread() {
return looper == Looper.myLooper();
}
@Override
public Poster createPoster(EventBus eventBus) {
return new HandlerPoster(eventBus, looper, 10);
}
}
mainThreadPoster在EventBus的构造方法中,通过mainThreadSupport.createPoster(EventBus eventBus)生成,是一个HandlerPoster对象,HandlerPoster实际上是一个Handler:
public class HandlerPoster extends Handler implements Poster {
private final PendingPostQueue queue; //post队列
private final int maxMillisInsideHandleMessage; //最大处理时长
private final EventBus eventBus;
private boolean handlerActive; //处理状态
//...
}
HandlerPoster 中持有一个 PendingPostQueue
对象,它是一个双向链表,链表对象PendingPost是发射事件event、订阅关系Subscription的封装类,并包含一个静态List
final class PendingPostQueue {
private PendingPost head;
private PendingPost tail;
synchronized void enqueue(PendingPost pendingPost) {
if (pendingPost == null) {
throw new NullPointerException("null cannot be enqueued");
}
if (tail != null) {
tail.next = pendingPost;
tail = pendingPost;
} else if (head == null) {
head = tail = pendingPost;
} else {
throw new IllegalStateException("Head present, but no tail");
}
notifyAll();
}
synchronized PendingPost poll() {
PendingPost pendingPost = head;
if (head != null) {
head = head.next;
if (head == null) {
tail = null;
}
}
return pendingPost;
}
synchronized PendingPost poll(int maxMillisToWait) throws InterruptedException {
if (head == null) {
wait(maxMillisToWait);
}
return poll();
}
}
HandlerPoster的事件入队方法:enqueue
public void enqueue(Subscription subscription, Object event) {
//取出的是PendingPost缓存池的最后一个对象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
//发送一个空消息
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
HandlerPoster的handleMessage方法:
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
//取出post队列中第一个事件
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
//调用EventBus的invokeSubscriber调用事件方法
eventBus.invokeSubscriber(pendingPost);
//判断是否超时
long timeInMethod = SystemClock.uptimeMillis() - started;
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
2. backgroundPoster
final class BackgroundPoster implements Runnable, Poster {
private final PendingPostQueue queue;
private final EventBus eventBus;
//维护执行状态
private volatile boolean executorRunning;
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
if (!executorRunning) {
executorRunning = true;
//通过线程池执行
eventBus.getExecutorService().execute(this);
}
}
}
}
backgroundPoster实现了Runnable接口,通过线程池来实现方法调用,他的run方法如下:
@Override
public void run() {
try {
try {
while (true) {
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
//依然是通过invokeSubscriber调用
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
我们可以看到,backgroundPoster与HandlerPoster调用逻辑基本一致,都是使用eventBus.invokeSubscriber(pendingPost)方法,不同在于HandlerPoster是通过handler在主线程执行,而backgroundPoster是通过线程池在子线程执行。
AsyncPoster
class AsyncPoster implements Runnable, Poster {
private final PendingPostQueue queue;
private final EventBus eventBus;
AsyncPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}
@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}
}
AsyncPoster与backgroundPoster不同之处在于:
- backgroundPoster使用synchronized锁住了
pendingPost = queue.poll();
和eventBus.getExecutorService().execute(this);
,这保证了backgroundPoster在事件入队和执行时是串行的。