EventBus 源码

构造方法

当要使用 EventBus 时,首先会调用 EventBus.getDefault() 来获取 EventBus 实例:

1
2
3
4
5
6
7
8
9
10
11
public static EventBus getDefault() {
// 双重检查模式(DCL)的单例模式
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}

接下来查看构造方法:

1
2
3
4
5
6
7
8
// class:EventBus
// EventBusBuilder 内部又调用到了 EventBus 的另一个构造方法
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

public EventBus() {
// DEFAULT_BUILDER 是默认的 EventBusBuilder,用来构造 EventBus。
this(DEFAULT_BUILDER);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// class:EventBus
// 可通过构造一个 EventBusBuilder 来对 EventBus 进行配置。建造者模式。
EventBus(EventBusBuilder builder) {
logger = builder.getLogger();
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
mainThreadSupport = builder.getMainThreadSupport();
mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
backgroundPoster = new BackgroundPoster(this);
asyncPoster = new AsyncPoster(this);
indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
logSubscriberExceptions = builder.logSubscriberExceptions;
logNoSubscriberMessages = builder.logNoSubscriberMessages;
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
throwSubscriberException = builder.throwSubscriberException;
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}

订阅者注册

获取 EventBus 后,便可以将订阅者注册到 EventBus 中:

1
2
3
4
5
6
7
8
9
10
11
12
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
// findSubscriberMethods 方法找出一个 SubscriberMethod 集合,也就是传进来的订阅者的所有订阅方法。
// SubscriberMethod 类中主要用来保存订阅方法的 Method 对象、线程模式、事件类型、优先级、是否是粘性事件等属性。
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
// 遍历集合,完成订阅者的注册操作。
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}

查找订阅者的订阅方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// 从缓存中查找是否有订阅方法的集合,如果找到了就立马返回。否则根据 ignoreGeneratedIndex 的值来选择采用何种方法来查找订阅方法的集合。
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);

if (subscriberMethods != null) {
return subscriberMethods;
}
// ignoreGeneratedIndex 属性表示是否忽略注解器生成的 MyEventBusIndex。
// 默认值 false,可通过 EventBusBuilder 来设置它的值。
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;
}
}

当通过 EventBus 单例模式来获取默认的 EventBus 对象,也就是 ignoreGeneratedIndex 为 false 的情况,会调用 findUsingInfo 方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 获取订阅者信息。在开始查找订阅方法时并没有忽略注解器生成的索引 MyEventBusIndex。如果通过 EventBusBuilder 配置了 MyEventBusIndex,便会获取 subscriberInfo。
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 {
// 如果没有配置 MyEventBusIndex,便会执行此方法,将订阅方法保存到 findState 中。
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
// 对 findState 做回收处理并返回订阅方法的 List 集合。
return getMethodsAndRelease(findState);
}

默认情况下是没有配置 MyEventBusIndex 的,因此查看 findUsingReflectionInSingleClass 方法:

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
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
// 通过反射来获取订阅者中所有方法,并根据方法的类型、参数和注解来找到订阅方法。找到订阅方法后将订阅方法的相关信息保存到 findState 中。
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 subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
if (findState.checkAdd(method, eventType)) {
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");
}
}
}

订阅者的注册过程

在查找完订阅者的订阅方法后便开始对所有的订阅方法进行注册,在 register() 中调用了 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
// 主要做了两件事:一是将 Subscriptions 根据 eventType 封装到 subscriptionsByEventType 中,将 subscribedEvents 根据 subscriber 封装到 typesBySubscriber 中。二是对粘性事件的处理。
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
// 根据订阅者和订阅方法创建一个订阅对象 Subscription。
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 根据事件类型获取订阅集合对象。
CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
// 如果为 null 则重新创建,并将 Subscriptions 根据 eventType 保存在 Map 集合。
subscriptions = new CopyOnWriteArrayList<>();
subscriptionsByEventType.put(eventType, subscriptions);
} else {
// 判断订阅者是否已经被注册
if (subscriptions.contains(newSubscription)) {
throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
+ eventType);
}
}

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) {
// 如果为 null 则重新创建,并将 eventType 添加到 subscribedEvents 中,并根据 subscriber 将 subscribedEvents 存储在 typesBySubscriber(Map 集合)。
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
subscribedEvents.add(eventType);
// 如果是粘性事件,则从 stickyEvents 事件保存队列中取出该事件类型的事件发送给当前订阅者。
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);
}
}
}

事件的发送

在获取 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
// class:EventBus
public void post(Object event) {
// PostingThreadState 保存着事件队列和线程状态信息。
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()) {
postSingleEvent(eventQueue.remove(0), postingState);
}
} finally {
postingState.isPosting = false;
postingState.isMainThread = false;
}
}
}
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
// class:EventBus
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
// 表示是否向上查找事件的父类,默认为 true,可在 EventBusBuilder 中进行配置。
if (eventInheritance) {
// 通过 lookupAllEventTypes 找到所有父类事件并存在 List 中
List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
int countTypes = eventTypes.size();
for (int h = 0; h < countTypes; h++) {
Class<?> clazz = eventTypes.get(h);
// 然后通过 postSingleEventForEventType 对事件逐一处理。
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));
}
}
}
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 boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 同步取出该事件对应的 Subscriptions(订阅对象集合)。
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 遍历 Subscriptions,将事件 event 和对应的 Subscription(订阅对象)传递给 postingState 并调用 postToSubscription 方法对事件进行处理。
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;
}
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
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
// 取出订阅方法的 threadMode(线程模式),之后据其来分别处理。
switch (subscription.subscriberMethod.threadMode) {
case POSTING:
invokeSubscriber(subscription, event);
break;
case MAIN:
if (isMainThread) {
// 若提交事件的线程是主线程,则通过反射直接运行订阅的方法。
invokeSubscriber(subscription, event);
} else {
// 若其不是主线程,则需要 mainThreadPoster 将订阅事件添加到主线程队列中。
// mainThreadPoster 是 HandlerPoster 类型的,继承自 Handler,通过 Handler 将订阅方法切换到主线程执行。
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);
}
}

订阅者取消注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public synchronized void unregister(Object subscriber) {
// typesBySubscriber 是一个 map 集合。通过 subscriber 找到 subscribedTypes(事件类型集合)。
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
// 遍历 subscribedTypes,并调用 unsubscribeByEventType 方法。
unsubscribeByEventType(subscriber, eventType);
}
// 将 subscriber 对应的 eventType 从 typesBySubscriber 中移除。
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
// 通过 eventType 来得到对应的 Subscriptions(订阅对象集合)
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
// 并在 for 循环中判断如果 Subscription(订阅对象) 的 subscriber(订阅者) 属性等于传进来的 subscriber,则从 Subscriptions 中移除该 Subscription。
Subscription subscription = subscriptions.get(i);
if (subscription.subscriber == subscriber) {
subscription.active = false;
subscriptions.remove(i);
i--;
size--;
}
}
}
}

链接

参考资料:

GitHub

Android 进阶之光