拆轮子系列之剖析EventBus源码

EventBus

EventBus是我们在项目当中最常用的开源框架之一。对于EventBus的使用方法也是非常的简单。然而EventBus内部的实现原理也不是很复杂。在这里便针对EventBus3.0的源码进行一下详细的分析。对于EventBus的详细使用可以参考EventBus 3.0初探: 入门使用及其使用 完全解析这篇文章

创建

要想注册成为订阅者,必须在一个类中调用如下:

1
EventBus.getDefault().register(this);

那么,我们看一下getDefault()的源码是怎样的,EventBus#getDefault()

1
2
3
4
5
6
7
8
9
10
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}

可以看出,这里使用了单例模式,而且是双重校验的单例,确保在不同线程中也只存在一个EvenBus的实例。
看看EventBus的构造方法:

1
2
3
public EventBus() {
this(DEFAULT_BUILDER);
}

从注解我们看到,每一个EventBus都是独立地、处理它们自己的事件,因此可以存在多个EventBus,而通过getDefault()方法获取的实例,则是它已经帮我们构建好的EventBus,是单例,无论在什么时候通过这个方法获取的实例都是同一个实例。除此之外,我们可以通过建造者帮我们建造具有不同功能的EventBus。
我们继续看上面的this(DEFAULT_BUILDER)调用了另一个构造方法:

1
2
3
4
5
6
7
8
9
EventBus(EventBusBuilder builder) {
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
//一系列的builder赋值
}

可以看出,对成员变量进行了一系列的初始化,那么我们来看看几个关键的成员变量:

1
2
3
private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
private final Map<Object, List<Class<?>>> typesBySubscriber;
private final Map<Class<?>, Object> stickyEvents;

subscriptionsByEventType:以event(即事件类)为key,以订阅列表(Subscription)为value,事件发送之后,在这里寻找订阅者,而Subscription又是一个CopyOnWriteArrayList,这是一个线程安全的容器。你们看会好奇,Subscription到底是什么,其实看下去就会了解的,现在先提前说下:Subscription是一个封装类,封装了订阅者、订阅方法这两个类。
typesBySubscriber:以订阅者类为key,以event事件类为value,在进行register或unregister操作的时候,会操作这个map。
stickyEvents:保存的是粘性事件

回到EventBus的构造方法,接下来实例化了三个Poster,分别是mainThreadPoster、backgroundPoster、asyncPoster等,这三个Poster是用来处理发送事件而进行线程切换的,我们下面会展开讲述。接着,就是对builder的一系列赋值了,这里使用了建造者模式

这里的建造者是EventBusBuilder,它的一系列方法用于配置EventBus的属性,使用getDefault()方法获取的实例,会有着默认的配置,上面说过,EventBus的构造方法是公有的,所以我们可以通过给EventBusBuilder设置不同的属性,进而获取有着不同功能的EventBus。那么我们来列举几个常用的属性加以讲解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//默认地,EventBus会考虑事件的超类,即事件如果继承自超类,那么该超类也会作为事件发送给订阅者。
//如果设置为false,则EventBus只会考虑事件类本身。
boolean eventInheritance = true;
public EventBusBuilder eventInheritance(boolean eventInheritance) {
this.eventInheritance = eventInheritance;
return this;
}
//当订阅方法是以onEvent开头的时候,可以调用该方法来跳过方法名字的验证,订阅这类会保存在List中
List<Class<?>> skipMethodVerificationForClasses;
public EventBusBuilder skipMethodVerificationFor(Class<?> clazz) {
if (skipMethodVerificationForClasses == null) {
skipMethodVerificationForClasses = new ArrayList<>();
}
skipMethodVerificationForClasses.add(clazz);
return this;
}
//更多的属性配置请参考源码,均有注释
//...

那么,我们通过建造者模式来手动创建一个EventBus,而不是使用getDefault()方法:

1
2
3
4
5
EventBus eventBus = EventBus.builder()
.eventInheritance(false)
.sendNoSubscriberEvent(true)
.skipMethodVerificationFor(MainActivity.class)
.build();

注册

要想使一个类成为订阅者,那么这个类必须有一个订阅方法,以@Subscribe注解标记的方法,接着调用register()方法来进行注册。那么我们直接来看EventBus#register()

1
2
3
4
5
6
7
8
9
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>中,由此可推测通过上面的方法把订阅方法找出来了,并保存在集合中,那么我们直接看这个方法SubscriberMethodFinder#findSubscriberMethods()

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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;
}
}

从上面的逻辑可以知道,一般会调用findUsingInfo方法,我们接着看SubscriberMethodFinder#findUsingInfo方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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这个内部类来保存订阅者类的信息,我们看看它的内部结构:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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进行保存,我们来看这个方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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则是用于保存订阅方法的一个类。

FindState#checkAdd深入的一系列方法的作用:

  • 允许一个类有多个参数相同的订阅方法
  • 子类继承并重写了父类的订阅方法,那么只会把子类的订阅方法添加到订阅者列表,父类的方法会忽略

当遍历完当前类的所有方法后,会回到findUsingInfo方法,接着会执行最后一行代码,即return getMethodsAndRelease(findState);那么我们继续看SubscriberMethodFinder#getMethodsAndRelease方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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不断逐层返回,直到返回EventBus#register()方法,最后开始遍历每一个订阅方法,并调用subscribe(subscriber, subscriberMethod)方法,那么,我们继续来看EventBus#subscribe方法。

在该方法内,主要是实现订阅方法与事件直接的关联,即注册,即放进我们上面提到关键的几个Map中:subscriptionsByEventType、typesBySubscriber、stickyEvents。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
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);
}
}
}

到目前为止,注册流程基本分析完毕,而关于最后的粘性事件的处理,这里暂时不说,后面再细说。

注销

与注册相对应的是注销,当订阅者不再需要事件的时候,我们要注销这个订阅者,即调用以下代码:

1
EventBus.getDefault().unregister(this);

那么我们来分析注销流程是怎样实现的,首先查看EventBus#unregister

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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,把订阅者以及事件作为参数传递了进去,那么应该是解除两者的联系。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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移除相应与订阅者有关的信息,注销流程相对于注册流程简单了很多,其实注销流程主要逻辑集中于怎样找到订阅方法上。

发送事件

接下来,我们分析发送事件的流程,一般地,发送一个事件调用以下代码:

1
EventBus.getDefault().post(new MessageEvent("Hello !....."));`

我们来看看EventBus#post方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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是什么呢?我们来看看它的类结构:

1
2
3
4
5
6
7
8
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又是什么呢?

1
2
3
4
5
6
private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
@Override
protected PostingThreadState initialValue() {
return new PostingThreadState();
}
};

原来 currentPostingThreadState是一个ThreadLocal,而ThreadLocal是每个线程独享的,其数据别的线程是不能访问的,因此是线程安全的。我们再次回到Post()方法,继续往下走,是一个while循环,这里不断地从队列中取出事件,并且分发出去,调用的是EventBus#postSingleEvent方法。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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));
}
}
}

从上面的逻辑来看,对于一个事件,默认地会搜索出它的父类,并且把父类也作为事件之一发送给订阅者,接着调用了EventBus#postSingleEventForEventType,把事件、postingState、事件的类传递进去,那么我们来看看这个方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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,可以发现,这里把订阅列表作为参数传递了进去,显然,订阅列表内部保存了订阅者以及订阅方法,那么可以猜测,这里应该是通过反射的方式来调用订阅方法。具体怎样的话,我们看源码。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
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,则要判断当前线程是否是MAIN线程,如果是也是直接调用invokeSubscriber()方法,否则会交给mainThreadPoster来处理,其他情况相类似。这里会用到三个Poster,由于粘性事件也会用到这三个Poster,因此我把它放到下面来专门讲述。而EventBus#invokeSubscriber的实现也很简单,主要实现了利用反射的方式来调用订阅方法,这样就实现了事件发送给订阅者,订阅者调用订阅方法这一过程。如下所示:

1
2
3
4
5
6
7
8
9
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);
}
}

粘性事件的发送及接收分析

粘性事件与一般的事件不同,粘性事件是先发送出去,然后让后面注册的订阅者能够收到该事件。粘性事件的发送是通过EventBus#postSticky()方法进行发送的,我们来看它的源码:

1
2
3
4
5
6
7
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);
}

把该事件放进了 stickyEvents这个map中,接着调用了post()方法,那么流程和上面分析的一样了,只不过是找不到相应的subscriber来处理这个事件罢了。那么为什么当注册订阅者的时候可以马上接收到匹配的事件呢?还记得上面的EventBus#subscribe方法里面有一段是专门处理粘性事件的代码吗?即:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
//以上省略...
//下面是对粘性事件的处理
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并不知道当前的订阅者对应了哪个粘性事件,因此需要全部遍历一次,找到匹配的粘性事件后,会调用EventBus#checkPostStickyEventToSubscription方法:

1
2
3
4
5
6
7
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
if (stickyEvent != null) {
// If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
// --> Strange corner case, which we don't take care of here.
postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());
}
}

接着,又回到了postToSubscription方法了,无论对于普通事件或者粘性事件,都会根据threadMode来选择对应的线程来执行订阅方法,而切换线程的关键所在就是mainThreadPoster、backgroundPoster和asyncPoster这三个Poster。

HandlerPoster

我们首先看mainThreadPoster,它的类型是HandlerPoster继承自Handler:

1
2
3
4
5
6
7
8
9
10
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方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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线程:

1
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
@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:

1
2
3
4
5
6
7
8
9
10
11
12
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()方法,使用的是newCachedThreadPool线程池来创建线程并执行的任务,run()方法内部也是调用到了EventBus#invokeSubscriber方法。

AsyncPoster

与BackgroundPoster类似,它也是一个Runnable,实现原理与BackgroundPoster大致相同,但有一个不同之处,就是它内部不用判断之前是否已经有一条线程已经在运行了,它每次post事件都会使用新的一条线程。同样使用到了线程池:

1
2
3
4
5
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}

观察者模式

整个EventBus是基于观察者模式而构建的,而上面的调用观察者的方法则是观察者模式的核心所在。

从整个EventBus可以看出,事件是被观察者,订阅者类是观察者,当事件出现或者发送变更的时候,会通过EventBus通知观察者,使得观察者的订阅方法能够被自动调用。当然了,这与一般的观察者模式有所不同。EventBus就充当了中介的角色,把事件的很多责任抽离出来,使得事件自身不需要实现任何东西,别的都交给EventBus来操作就可以了。

参考博文链接1
参考博文链接2
参考博文链接3