看了好几次EventBus源码了,这次总算基本上搞清楚了,简单来说就是调用 EventBus.getDefault().register(this),将订阅者类(如下MainActivity)中所有订阅方法(如下onMessageEvent方法)存下来,然后某个对象在调用EventBus.getDefault().post(new MsgEvent())时,实际上是通过反射调用之前存好的订阅方法,本文分为以下几个部分:注册、销毁、发送事件来解读EventBus。
基本用法
我把基本用法的代码贴出来,方便我们查看,并根据代码来理解其逻辑:
消息事件:
public class MsgEvent {
}
应用类:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EventBus.getDefault().register(this);
EventBus.getDefault().post(new MsgEvent());
}
@Override
protected void onDestroy() {
super.onDestroy();
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MsgEvent event) {
Log.d("tag","******just a event****");
};
}
我们主要从注册事件EventBus.getDefault().register(this);发送事件EventBus.getDefault().post(new MsgEvent()); 取消注册事件EventBus.getDefault().unregister(this);来开始分析EventBus。
重要的数据结构
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
private final Map<Class<?>, Object> stickyEvents;
final class Subscription {
final Object subscriber;
final SubscriberMethod subscriberMethod;
volatile boolean active;
Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
this.subscriber = subscriber;
this.subscriberMethod = subscriberMethod;
active = true;
}
...此处省略
}
subscriptionsByEventType:以event(即事件类)为key,以订阅列表(Subscription)为value,事件发送之后,在这里寻找订阅者,而Subscription又是一个CopyOnWriteArrayList,这是一个线程安全的容器。你们看会好奇,Subscription到底是什么,其实看下去就会了解的,现在先提前说下:Subscription是一个封装类,封装了订阅者、订阅方法这两个类。
typesBySubscriber:以订阅者类为key,以event事件类为value,在进行register或unregister操作的时候,会操作这个map。
stickyEvents:保存的是粘性事件,粘性事件上一篇文章有详细描述。
回到EventBus的构造方法,接下来实例化了三个Poster,分别是mainThreadPoster、backgroundPoster、asyncPoster等,这三个Poster是用来处理粘性事件的,我们下面会展开讲述。接着,就是对builder的一系列赋值了,这里使用了建造者模式。
Subscription:以订阅者为key(类比上面的MainActivity),以订阅者中方法(类比上面的onMessageEvent方法)为value。
注册事件
要想注册成为订阅者,必须在一个类中调用如下:
EventBus.getDefault().register(this);
那么,我们看一下getDefault()的源码是怎样的,EventBus#getDefault():
getDefault()
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
可以看出,这里使用了单例模式,而且是双重校验的单例,确保在不同线程中也只存在一个EvenBus的实例。
register
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
先获取了订阅者类的class,接着交给SubscriberMethodFinder.findSubscriberMethods()处理,返回结果保存在List<SubscriberMethod>(即上面的onMessageEvent)中,由此可推测通过上面的方法把订阅方法找出来了,并保存在集合中。
为了方便读者理解,具体findSubscriberMethods()分析在最后一节。
在找到订阅者中所有的方法集合subscriberMethods后,将执行subscribe(subscriber, subscriberMethod),生成subscription,将所有subscription都添加到subscriptionsByEventType变量中,获取subscriberMethod的类型,并赋值给typesBySubscriber。
subscribe
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
//将subscriber和subscriberMethod封装成 Subscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
//根据事件类型获取特定的 Subscription
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
//如果为null,说明该subscriber尚未注册该事件
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
//如果不为null,并且包含了这个subscription 那么说明该subscriber已经注册了该事件,抛出异常
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;
}
}
//根据subscriber(订阅者)来获取它的所有订阅事件
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
//把订阅者、事件放进typesBySubscriber这个Map中
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
//下面是对粘性事件的处理
if (subscriberMethod.sticky) {
//从EventBusBuilder可知,eventInheritance默认为true.
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 {
//根据eventType,从stickyEvents列表中获取特定的事件
Object stickyEvent = stickyEvents.get(eventType);
//分发事件
checkPostStickyEventToSubscription(newSubscription, stickyEvent);
}
}
}
到目前为止,注册流程基本分析完毕。
发送事件
EventBus.getDefault().post(new MessageEvent());`
post
public void post(Object event) {
//1、 获取一个postingState
PostingThreadState postingState = currentPostingThreadState.get();
List<Object> eventQueue = postingState.eventQueue;
//将事件加入队列中
eventQueue.add(event);
if (!postingState.isPosting) {
//判断当前线程是否是主线程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
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;
}
}
}
首先是获取一个PostingThreadState,那么PostingThreadState是什么呢?我们来看看它的类结构:
PostingThreadState
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}
可以看出,该PostingThreadState主要是封装了当前线程的信息,以及订阅者、订阅事件等。那么怎么得到这个PostingThreadState呢?让我们回到post()方法,看①号代码,这里通过currentPostingThreadState.get()来获取PostingThreadState。那么currentPostingThreadState又是什么呢?
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};
原来 currentPostingThreadState是一个ThreadLocal,而ThreadLocal是每个线程独享的,其数据别的线程是不能访问的,因此是线程安全的。我们再次回到Post()方法,继续往下走,是一个while循环,这里不断地从队列中取出事件,并且分发出去,调用的是EventBus#postSingleEvent方法。
postSingleEvent
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
//该eventInheritance上面有提到,默认为true,即EventBus会考虑事件的继承树
//如果事件继承自父类,那么父类也会作为事件被发送
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) {
Log.d(TAG, "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) {
//从subscriptionsByEventType获取响应的subscriptions
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;
}
//...
}
return true;
}
return false;
}
接着,进一步调用了EventBus#postToSubscription,可以发现,这里把订阅列表作为参数传递了进去,显然,订阅列表内部保存了订阅者以及订阅方法,那么可以猜测,这里应该是通过反射的方式来调用订阅方法。具体怎样的话,我们看源码。
postToSubscription
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 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,即订阅方法运行的线程,如果是POSTING,那么直接调用invokeSubscriber()方法即可,如果是MAIN,则要判断当前线程(post事件的线程)是否是MAIN线程,如果是也是直接调用invokeSubscriber()方法,否则会交给mainThreadPoster来处理,其他情况相类似。
invokeSubscriber
主要利用反射的方式来调用订阅方法,这样就实现了事件发送给订阅者,订阅者调用订阅方法这一过程。如下所示:
void invokeSubscriber(Subscription subscription, Object event) {
try {
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
}
//...
}
HandlerPoster
我们首先看mainThreadPoster,它的类型是HandlerPoster继承自Handler:
final class HandlerPoster extends Handler {
//PendingPostQueue队列,待发送的post队列
private final PendingPostQueue queue;
//规定最大的运行时间,因为运行在主线程,不能阻塞主线程
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
private boolean handlerActive;
//省略...
}
可以看到,该handler内部有一个PendingPostQueue,这是一个队列,保存了PendingPost,即待发送的post,该PendingPost封装了event和subscription,方便在线程中进行信息的交互。在postToSubscription方法中,当前线程如果不是主线程的时候,会调用HandlerPoster#enqueue方法:
void enqueue(Subscription subscription, Object event) {
//将subscription和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");
}
}
}
}
首先会从PendingPostPool中获取一个可用的PendingPost,接着把该PendingPost放进PendingPostQueue,发送消息,那么由于该HandlerPoster在初始化的时候获取了UI线程的Looper,所以它的handleMessage()方法运行在UI线程:
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
//不断从队列中取出pendingPost
while (true) {
//省略...
eventBus.invokeSubscriber(pendingPost);
//..
}
} finally {
handlerActive = rescheduled;
}
}
里面调用到了EventBus#invokeSubscriber方法,在这个方法里面,将PendingPost解包,进行正常的事件分发,这上面都说过了,就不展开说了。
BackgroundPoster
BackgroundPoster继承自Runnable,与HandlerPoster相似的,它内部都有PendingPostQueue这个队列,当调用到它的enqueue的时候,会将subscription和event打包成PendingPost:
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
queue.enqueue(pendingPost);
//如果后台线程还未运行,则先运行
if (!executorRunning) {
executorRunning = true;
//会调用run()方法
eventBus.getExecutorService().execute(this);
}
}
}
该方法通过Executor来运行run()方法,run()方法内部也是调用到了EventBus#invokeSubscriber方法。
AsyncPoster
与BackgroundPoster类似,它也是一个Runnable,实现原理与BackgroundPoster大致相同,但有一个不同之处,就是它内部不用判断之前是否已经有一条线程已经在运行了,它每次post事件都会使用新的一条线程。
注销
与注册相对应的是注销,当订阅者不再需要事件的时候,我们要注销这个订阅者,即调用以下代码:
EventBus.getDefault().unregister(this);
那么我们来分析注销流程是怎样实现的,首先查看EventBus#unregister:
unregister
public synchronized void unregister(Object subscriber) {
//根据当前的订阅者来获取它所订阅的所有事件
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
//遍历所有订阅的事件
for (Class<?> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
//从typesBySubscriber中移除该订阅者
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
上面调用了EventBus#unsubscribeByEventType,把订阅者以及事件作为参数传递了进去,那么应该是解除两者的联系。
unsubscribeByEventType
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
//根据事件类型从subscriptionsByEventType中获取相应的 subscriptions 集合
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
//遍历所有的subscriptions,逐一移除
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}
可以看到,上面两个方法的逻辑是非常清楚的,都是从typesBySubscriber或subscriptionsByEventType移除相应与订阅者有关的信息,注销流程相对于注册流程简单了很多,其实注册流程主要逻辑集中于怎样找到订阅方法上。
继续分析findSubscriberMethods
findSubscriberMethods
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
//首先从缓存中取出subscriberMethodss,如果有则直接返回该已取得的方法
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
//从EventBusBuilder可知,ignoreGenerateIndex一般为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 {
//将获取的subscriberMeyhods放入缓存中
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
findSubscriberMethods通过调用findUsingInfo来找到订阅者中的所有方法集合。
findUsingInfo
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
//准备一个FindState,该FindState保存了订阅者类的信息
FindState findState = prepareFindState();
//对FindState初始化
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
//获得订阅者的信息,一开始会返回null
findState.subscriberInfo = getSubscriberInfo(findState);
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 {
//1 、到了这里
findUsingReflectionInSingleClass(findState);
}
//移动到父类继续查找
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
上面用到了FindState这个内部类来保存订阅者类的信息,我们看看它的内部结构:
FindState
static class FindState {
//订阅方法的列表
final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
//以event为key,以method为value
final Map<Class, Object> anyMethodByEventType = new HashMap<>();
//以method的名字生成一个method为key,以订阅者类为value
final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
final StringBuilder methodKeyBuilder = new StringBuilder(128);
Class<?> subscriberClass;
Class<?> clazz;
boolean skipSuperClasses;
SubscriberInfo subscriberInfo;
//对FindState初始化
void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}
//省略...
}
可以看出,该内部类保存了订阅者及其订阅方法的信息,用Map一一对应进行保存,接着利用initForSubscriber进行初始化,这里subscriberInfo初始化为null,因此在SubscriberMethodFinder#findUsingInfo里面,会直接调用到①号代码,即调用SubscriberMethodFinder#findUsingReflectionInSingleClass,这个方法非常重要!!!在这个方法内部,利用反射的方式,对订阅者类进行扫描,找出订阅方法,并用上面的Map进行保存,我们来看这个方法。
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();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
//获取方法的参数类型
Class<?>[] parameterTypes = method.getParameterTypes();
//如果参数个数为一个,则继续
if (parameterTypes.length == 1) {
//获取该方法的@Subscribe注解
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
//参数类型 即为 事件类型
Class<?> eventType = parameterTypes[0];
// 2 、调用checkAdd方法
if (findState.checkAdd(method, eventType)) {
//从注解中提取threadMode
ThreadMode threadMode = subscribeAnnotation.threadMode();
//新建一个SubscriberMethod对象,并添加到findState的subscriberMethods这个集合内
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
//如果开启了严格验证,同时当前方法又有@Subscribe注解,对不符合要求的方法会抛出异常
} 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");
}
}
}
虽然该方法比较长,但是逻辑非常清晰,逐一扫描订阅者内所有的方法,并判断订阅者类中是否存在订阅方法,如果符合要求,并且②号代码调用FindState#checkAdd方法返回true的时候,才会把方法保存在findState的subscriberMethods内。而SubscriberMethod则是用于保存订阅方法的一个类。
回到findUsingReflectionInSingleClass方法,当遍历完当前类的所有方法后,会回到findUsingInfo方法,接着会执行最后一行代码,即return getMethodsAndRelease(findState);
getMethodsAndRelease
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
//从findState获取subscriberMethods,放进新的ArrayList
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
//把findState回收
findState.recycle();
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
通过该方法,把subscriberMethods返回。