EventBus 是什么呢?即便是初入门的 Android 开发者,可能也会知道一点。它是针对 Android 的一个事件 发布/订阅 的框架,通过解耦发布者和订阅者,来简化 Android 事件传递。
一、EventBus 基本使用
EventBus 充分解耦了发布者和订阅者,使得代码更加简洁。它的使用也是非常简单:
EventBus.getDefault().register(this);
上述的代码,创建了一个订阅者,在不需要订阅的时候,需要进行反注册:
EventBus.getDefault().unregister(this);
除此之外,我们还需要为订阅者定义接收事件的方法,方法需要加上 @Subscribe 的注解:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onHotCityMessageEvent(T event) {
}
使用是比较简单的,接下来看源码的分析。
二、 register() 流程分析
/**
* Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
* are no longer interested in receiving events.
* <p/>
* Subscribers have event handling methods that must be annotated by {@link Subscribe}.
* The {@link Subscribe} annotation also allows configuration like {@link
* ThreadMode} and priority.
*/
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
// 1、找到订阅者所有被 @Subscribe 修饰的方法
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
// 2、遍历所有的订阅方法,进行真正的注册,会生成一个 Subscription
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
通过方法注释,我们可以知道:
- 订阅者需要调用 register() 进行注册,在不需要使用的时候调用 unRegister() 进行反注册。
- 订阅者接收事件,需要有被 @Subscribe 修饰的方法,此外还可以在注解中设置 ThreadMode,关于 ThreadMode,后面再展开。
通过对上述代码的阅读,我们还有两个疑问:
- 订阅者的订阅方法是如何被找到的?
- 注册的这个过程又是怎么样的?
1、找到订阅者中所有被 @Subscribe 修饰的方法
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 1、先从缓存中取,如果缓存命中的话,直接返回
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
if (ignoreGeneratedIndex) {
// 2、通过反射的方法获取
subscriberMethods = findUsingReflection(subscriberClass);
} else {
// 3、通过编译注解器获取,这是默认的获取方式,能够降低反射对性能的损耗
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;
}
}
获取注解方法的方式可以分为两种,一种是通过反射,另一种是在编译期通过注解处理器进行解析处理,生成订阅者的订阅信息。限于篇幅,并且这篇文章主要是对于整体的流程的把控,就不追究具体的细节了,感兴趣的同学可以自行去阅读相关的源码。
2、 通过 subscribe 完成注册
找到所有被 @Subscribe 修饰的方法之后,就需要执行真正的注册工作了,接下来看具体的流程:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 1、获取事件的类型
Class<?> eventType = subscriberMethod.eventType;
// 2、根据当前的事件类型以及订阅者创建一个 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 3、根据事件的类型,获取所有订阅了该事件的订阅者
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
// 4、如果该事件是第一次订阅,就会创建一个订阅者的集合,并存入到 subscriptionsByEventType
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}
// 5、根据事件的优先级,存入到合适的位置
int size = subscriptions.size();
for (int i = 0; i <= size; i++) {
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
// 6、获取订阅者所有的订阅事件,并添加到 typesBySubscriber 中
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
// 7、处理粘性事件,会立即把该事件 post 给订阅者
if (subscriberMethod.sticky) {
if (eventInheritance) {
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
for (Map.Entry<Class<?>, 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);
}
}
}
接下来看一张流程图,结束 register() 的分析:
三、post() 流程分析
public void post(Object event) {
// 1、获取当前线程的 Posting 状态,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()) {
// 2、post 单个事件
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
接下来重点看处理单个事件的流程:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
// 1、是否触发了该事件对应的父类,以及接口对应的响应方法,默认情况下为 true
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 {
// 2、寻找本次事件的对应的订阅者,并把本次事件交给对应的订阅者
subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
}
// 3、如果没有找到对应的订阅者
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<Subscription> subscriptions;
synchronized (this) {
// 1、通过 eventType ,获取所有的订阅者
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 2、遍历所有的订阅者,把消息交给每一个订阅者处理
for (Subscription subscription : subscriptions) {
postingState.event = event;
postingState.subscription = subscription;
boolean aborted;
try {
// 3、消息交给订阅者处理
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);
}
}
这里涉及到 ThreadMode,ThreadMode 有五种,下面分别解释一下:
- POSTING:订阅者在发布线程的事件中直接调用,这是默认的模式。
- MAIN:订阅者的的响应方法在主线程中完成,响应方法中不能有耗时的操作,
- BACKGROUND:在后台的线程中调用,如果发布线程不是主线程,则直接进行调用,否则开启一个后台线程去处理。
- ASYNC:不论发布线程是否为主线程,都启动一个后台线程进行处理。
四、总结
现在来总结一下:
观察者模式是一个多对一的依赖,多个观察者对某一个事件进行注册,当事件发生了的时候就会去通知对应的观察者。具体到实现这种模式,需要注意一下几点:
- 应该考虑有两种集合,一个是根据事件类型,存储了所有的观察者;另一个是根据某一个订阅者,存储了该订阅者所有的响应事件。
- 还需要考虑对粘性事件的处理,在 postSticky() 的时候,先用一个集合把事件存储起来。在register() 订阅者的时候,会对该订阅者所有的事件函数进行遍历,如果发现了粘性事件,就会立即 post 该事件给当前的订阅者。