EventBus源码分析
前言
EventBus是我做安卓开发以来,接触最早的一个第三方依赖库,当年早期刚接触的时候,觉得太神奇了,这个异步事件处理起来太好用了,比自己开线程,获得对象锁,通知异步执行,这种繁杂的操作好多了,简直优雅!今天决定挖挖这个EventBus里面的玄机。
Android 开发中使用的发布/订阅事件总线框架,基于观察者模式,下面摘录官网一段简介:
EventBus is an open-source library for Android and Java using the publisher/subscriber pattern for loose coupling. EventBus enables central communication to decoupled classes with just a few lines of code – simplifying the code, removing dependencies, and speeding up app development.
翻译过来大意就是:
EventBus是适用于Android和Java的开源库,使用发布者/订阅者模式进行松散耦合。 EventBus使中央通信只需几行代码即可解耦类,从而简化了代码,消除了依赖关系并加快了应用程序的开发。
注解
EventBus从3.0开始,使用注解方式来配置事件订阅方法,不再使用方法名
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
ThreadMode threadMode() default ThreadMode.POSTING;
boolean sticky() default false;
int priority() default 0;
}
所以在使用Subscribe
注解时可以根据需求指定threadMode
、sticky
、priority
三个属性。这样我们就可以配置我们的订阅方法,事件类型可以自定义
@Subscribe(threadMode = ThreadMode.MAIN)
public void callbackEvent(final MsgEvent msgEvent) {
}
public enum ThreadMode {
POSTING,
MAIN,
MAIN_ORDERED,
BACKGROUND,
ASYNC
}
ThreadMode是枚举类型,
POSTING,默认值,在哪个线程发送事件就在对应线程处理事件,避免了线程切换,效率高
MAIN,在主线程消费事件,不管事件在哪个线程产生。发送如在主线程(UI线程)发送事件,则直接在主线程处理事件;如果在子线程发送事件,则先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件
MAIN_ORDERED,无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件
BACKGROUND,如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件;如果在子线程发送事件,则直接在发送事件的线程处理事件
ASYNC,无论在那个线程发送事件,都将事件入队列,然后通过线程池处理
注册事件
public void register(Object subscriber) {
// 得到当前要注册类的Class对象
Class<?> subscriberClass = subscriber.getClass();
// 根据Class查找当前类中订阅了事件的方法集合,即使用了Subscribe注解、有public修饰符、一个参数的方法
// SubscriberMethod类主要封装了符合条件方法的相关信息:
// Method对象、线程模式、事件类型、优先级、是否是粘性事等
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
//循环遍历订阅了事件的方法集合,来完成注册
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
在注册中,首先是通过注册类,查找订阅了事件的方法集合,SubscriberMethod类包含了Method对象、线程模式、事件类型、优先级、是否是粘性事等,
public class SubscriberMethod {
final Method method;
final ThreadMode threadMode;
final Class<?> eventType;
final int priority;
final boolean sticky;
/** Used for efficient comparison */
String methodString;
}
findSubscriberMethods中来查找当前类中订阅事件的方法集合,分析代码:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//METHOD_CACHE是缓存,ConcurrentHashMap类型,看缓存中有没有
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//EventBusBuilder中的ignoreGeneratedIndex属性默认为false,默认忽略注解生成器
if (ignoreGeneratedIndex) {
subscriberMethods = findUsingReflection(subscriberClass);
} else {
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;
}
}
EventBusBuilder是在EventBus单例模式中初始化,这里不展开。findSubscriberMethods的逻辑很清楚,先在缓存中查找,如果查找不到,进行下一步查找,找到后缓存到METHOD_CACHE中,如果缓存中找到了,直接返回,在findUsingInfo完成查找,代码如下:
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
//条件成立
while (findState.clazz != null) {
findState.subscriberInfo = getSubscriberInfo(findState);
//条件不成立,subscriberInfo为null
if (findState.subscriberInfo != null) {
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
//通过反射找到订阅事件的方法
findUsingReflectionInSingleClass(findState);
}
//遍历父类,
findState.moveToSuperclass();
}
// 查找到的方法保存在了FindState实例的subscriberMethods集合中。
// 使用subscriberMethods构建一个新的List<SubscriberMethod>
// 释放掉findState
return getMethodsAndRelease(findState);
}
初始化一个FindState类,在initForSubscriber初始化订阅方法的类,
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
findUsingReflectionInSingleClass类查找订阅方法
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
//找到订阅类中的所有方法
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
//方法的修饰符
int modifiers = method.getModifiers();
//方法必须是public
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//当前方法所有参数
Class<?>[] parameterTypes = method.getParameterTypes();
//只能有一个参数
if (parameterTypes.length == 1) {
//拿到Subscribe的注解,使用Subscribe注解的方法,subscribeAnnotation不为null
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
//获取传入参数的类型
Class<?> eventType = parameterTypes[0];
//checkAdd()方法用来判断FindState的anyMethodByEventType map是否已经添加过以当前eventType为key的键值对,没添加过则返回true
if (findState.checkAdd(method, eventType)) {
// 创建一个SubscriberMethod对象,并添加到subscriberMethods集合
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException("@Subscribe method " + methodName +
"must have exactly 1 parameter but has " + parameterTypes.length);
}
} else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) {
String methodName = method.getDeclaringClass().getName() + "." + method.getName();
throw new EventBusException(methodName +
" is a illegal @Subscribe method: must be public, non-static, and non-abstract");
}
}
}
在findUsingReflectionInSingleClass中完成了当前类和父类的查找订阅方法的集合,继续看注册流程的subscribe方法
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//得到当前订阅事件的方法的参数类型
Class<?> eventType = subscriberMethod.eventType;
//Subscription保存了订阅类和订阅方法
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//查找 ,不存在添加 到subscriptionsByEventType
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
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);
}
}
//添加到subscriptions
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;
}
}
//typesBySubscriber的key值是订阅类,保存了以当前要注册类的对象为key,注册类中订阅事件的方法的参 //数类型的集合为value的键值对
// 查找是否存在对应的参数类型集合
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
//将订阅方法的参数添加到集合
subscribedEvents.add(eventType);
//粘性事件处理,单独分析
if (subscriberMethod.sticky) {
if (eventInheritance) {
// Existing sticky events of all subclasses of eventType have to be considered.
// Note: Iterating over all events may be inefficient with lots of sticky events,
// thus data structure should be changed to allow a more efficient lookup
// (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
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);
}
}
}
可以看出,subscribe方法主要是将subscriptionsByEventType、typesBySubscriber两个HashMap对应的数据类型add进去,其中subscriptionsByEventType的结构如下图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Vkttuvys-1593137750287)(file:///C:/Users/LIXUEC~1/AppData/Local/Temp/msohtmlclip1/01/clip_image002.png)]
总结注册过程,主要是完成将注册方法类,还有订阅方法,以及订阅方法的参数通过HasHMap进行保存,其中订阅方法集合通过反射拿到订阅方法修饰符、订阅方法的参数必须仅一个,必须是Subscribe的注解来筛选出来。最后保存的HasHMap的key值是subscriber,即注册方法所在的类。后面取消注册、发送事件的时候还会继续用到。
取消注册
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//删除以subscriber为key值的键值对
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
typesBySubscriber在注册的时候用到过,是一个HashMap,key值是订阅类,value是订阅方法的参数类型集合。第一步先通过订阅类作为key值来查出所有的该类所有订阅方法大的参数,之后通过unsubscribeByEventType方法来解除订阅,继续源码如下:
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
subscriptionsByEventType也是注册的时候用到的HashMap,这个方法先通过参数类型作为key值找到Subscription对象集合,通过上面的subscriptionsByEventType结构可以知道,Subscription对象成员包含subscriber(注册类)和SubscriberMethod(订阅方法),对Subscription对象集合直接操作,一个细节是size变量也在操作,不操作size直接删除数组元素,会有数组越界的风险。
发送事件
/** Posts the given event to the event bus. */
public void post(Object event) {
// currentPostingThreadState是一个PostingThreadState类型的ThreadLocal
// PostingThreadState是EventBus内部静态类,保存了事件队列和线程模式等信息
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
//默认false
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()) {
//发送单个事件,eventQueue是list类型,将事件从list中移出
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
currentPostingThreadState是一个PostingThreadState类型的ThreadLocal变量,关于ThreadLocal,源码注释如下:
/**
* This class provides thread-local variables. These variables differ from
* their normal counterparts in that each thread that accesses one (via its
* {@code get} or {@code set} method) has its own, independently initialized
* copy of the variable. {@code ThreadLocal} instances are typically private
* static fields in classes that wish to associate state with a thread (e.g.,
* a user ID or Transaction ID).
**/
翻译过来大意是:
ThreadLocal提供了线程的局部变量,每个线程都可以通过set()
和get()
来对这个局部变量进行操作,但不会和其他线程的局部变量进行冲突,实现了线程的数据隔离。也就是变量属于当前线程,有机会写一个ThreadLocal的源码阅读,因为Handler源码里面也用到了ThreadLocal
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
/** 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;
}
isMainThread方法做了是不是主线程的判断,怎么判断的呢?
public interface MainThreadSupport {
boolean isMainThread();
Poster createPoster(EventBus eventBus);
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);
}
}
}
通过Looper.myLooper(),是不是在Handler源码里面也涉及到这个Looper判断线程的操作,看来EventBus对Android适配性是很友好的。代码继续往下走,最后通过postSingleEvent发送事件
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
// eventInheritance默认为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 {
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处理
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 获取事件类型对应的Subscription集合
subscriptions = subscriptionsByEventType.get(eventClass);
}
//找到了订阅次类型事件的订阅者
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;
}
遍历subscriptions集合,通过postToSubscription处理
事件处理
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
// 判断订阅事件方法的线程模式
switch (subscription.subscriberMethod.threadMode) {
// 默认的线程模式,在那个线程发送事件就在那个线程处理事件
case POSTING:
invokeSubscriber(subscription, event);
break;
// 如果在主线程发送事件,则直接在主线程通过反射处理事件,否则加入队列,通过Handler切换到主线程助力
case MAIN:
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
//不管在哪个线程发送,都加入队列处理,通过Handler切换线程
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);
}
}
根据根据线程模式,可以有两种处理方式,其一是通过反射调用订阅方法,将事件类型等参数传递进去
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);
}
}
另外一种是将事件加入队列,实际上是实现了Poster接口,以mainThreadPoster为例
public class HandlerPoster extends Handler implements Poster {
private final PendingPostQueue queue;
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
protected HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
super(looper);
this.eventBus = eventBus;
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
// 封装一个PendingPost对象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
//加入队列
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
//handler处理
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) {
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(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;
}
}
}
所以HandlerPoster
的enqueue()
方法主要就是将subscription
、event
对象封装成一个PendingPost
对象,然后保存到队列里,之后通过Handler
切换到主线程,在handleMessage()
方法将中将PendingPost
对象循环出队列,交给invokeSubscriber()
方法进一步处理:
void invokeSubscriber(PendingPost pendingPost) {
Object event = pendingPost.event;
Subscription subscription = pendingPost.subscription;
PendingPost.releasePendingPost(pendingPost);
if (subscription.active) {
invokeSubscriber(subscription, event);
}
}
backgroundPoster和asyncPoster都是先将事件入队列,然后再出队列,但是会通过线程池去进一步处理事件,以asyncPoster为例,asyncPoster实现了Runnable, Poster接口,最终加入队列等待newCachedThreadPool类型线程池处理
asyncPosterpublic void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}
粘性事件
怎么理解这个粘性事件这个名词?我们知道,EventBus是基于观察者模式来设计的,那一个事件先有订阅者,再有发布者,这是一个正常调用流程,如果先有了发布者,再订阅,事件还能不能收到?如果能够收到,那就是所谓的粘性事件了。LiveData是也是基于观察者模式实现的,同样有粘性事件这样的功能(LiveData具有粘性问题会引发数据收到不想要的,不展开解释)。具体看EventBus实现粘性事件原理:
public void postSticky(Object event) {
synchronized (stickyEvents) {
stickyEvents.put(event.getClass(), event);
}
// Should be posted after it is putted, in case the subscriber wants to remove immediately
post(event);
}
可以看到postSticky()方法在发送粘性事件前,已经将对应类型事件的订阅者添加到stickyEvents中了,所以即使它是非粘性的,依然可以接收到发送出的粘性事件。后面的post方法和非粘性一样。
总结
EventBus通过注解、反射、Handler、线程池等技术,完成了观察者模式的设计,有非常多的技术细节值得学习借鉴。在3.0版本中,还有注解处理器的引用方式,暂时没有精力深入研究,总之,EventBus作为异步通信的框架,诞生很早,一直在更新前进,非常强大。