【源码分析】走进EventBus

时间:2022-10-23 09:20:42

简介

EventBus被广泛用于Android组件之间的通讯,源码点这里,当前的最新版本为3.0.0,该版本发布于2016.02.05。
它的大致原理如下图:
【源码分析】走进EventBus
根据官方的描述,它具有轻巧快速、解耦事件发送者和接收者、在各组件都运行稳定、避免了复杂的生命周期问题等等优点。

使用方法

它的使用方法很简单,相信大部分人都会了,在此赘述一下:
添加EventBus的依赖后,再进行如下3步操作

1 . 定义事件

public class MessageEvent {

public final String message;

public MessageEvent(String message) {
this.message = message;
}
}

2 . 准备订阅者

@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}

@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}

@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}

3 . 发送事件

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

源码分析

下面从源码来分析EventBus的原理

EventBus.getDefault().register(this);

先来看一下EventBus.getDefault();

    /** Convenience singleton for apps using a process-wide EventBus instance. */
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}

这里没啥好多说的,就是获取了EventBus的单例。
看一下它的构造方法

/**
* Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
* central bus, consider {@link #getDefault()}.
*/

public EventBus() {
this(DEFAULT_BUILDER);
}

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);
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;
}

可以看到,我们也能直接使用它的无参构造方法,但为了使用central bus,一般都使用getDefault()方法获取。
而这两种方式,用的都只能是同一个DEFAULT_BUILDER
DEFAULT_BUILDER是一个常量,我们先简单地看一下:

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

接着就是各种初始化,后面很多地方将用到这些变量。
看到这里,可以知道EventBus.getDefault()就是获取了EventBus的单例,并初始化了一些变量。
再往后,就到了register(this)

    /**
* 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();
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}

这里面主要干了两件事:
1. 第11行找出了”调用register(this)的类”包含的订阅者方法。
2. 第13至15行对找出的订阅者方法逐一进行订阅。
第11行的subscriberMethodFinder是在构造方法中初始化的,我们跟进findSubscriberMethods()方法看一看:

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}

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;
}
}

METHOD_CACHE是一个map对象,从第3至5行可以知道,在同一个类中调用多次register(this),只有第一次调用才真正有效。
第7至11行是真正寻找订阅者方法的地方。
第12至18行对找到的方法进行判断,如果找到了订阅者方法,则存入METHOD_CACHE并返回订阅者方法。如果没有订阅者方法,则抛出错误,从错误信息甚至可以得知这3点信息(从后面的代码也可以得到验证):

  1. 订阅者方法包括当前类的父类们中的订阅者方法。因此,父类们没有必要调用register(this)方法。
  2. 订阅者方法的访问权限修饰符必须是public
  3. 订阅者方法上必须有注解@Subscribe

第7行的ignoreGeneratedIndex也是之前在构造EventBus时赋值的,我们来看一下类EventBusBuilder中的一些变量:

public class EventBusBuilder {
private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();

boolean logSubscriberExceptions = true;
boolean logNoSubscriberMessages = true;
boolean sendSubscriberExceptionEvent = true;
boolean sendNoSubscriberEvent = true;
boolean throwSubscriberException;
boolean eventInheritance = true;
boolean ignoreGeneratedIndex;
boolean strictMethodVerification;
ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;
List<Class<?>> skipMethodVerificationForClasses;
List<SubscriberInfoIndex> subscriberInfoIndexes;

EventBusBuilder() {
}
……
……
……
}

很明显,ignoreGeneratedIndexfalse,刚才的代码会进入findUsingInfo(),其实它最终会和findUsingReflection()到达同一个方法。我们接着往下看:

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
while (findState.clazz != 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 {
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}

第1、2行实例化了一个FindState并将其初始化。
第4至17行遍历当前类和父类们,找寻订阅者方法,直至到达系统源码。
第16行就是将父类转变为迭代对象。
先看一下内部静态类FindState的相关方法:

private FindState prepareFindState() {
synchronized (FIND_STATE_POOL) {
for (int i = 0; i < POOL_SIZE; i++) {
FindState state = FIND_STATE_POOL[i];
if (state != null) {
FIND_STATE_POOL[i] = null;
return state;
}
}
}
return new FindState();
}

void initForSubscriber(Class<?> subscriberClass) {
this.subscriberClass = clazz = subscriberClass;
skipSuperClasses = false;
subscriberInfo = null;
}

void moveToSuperclass() {
if (skipSuperClasses) {
clazz = null;
} else {
clazz = clazz.getSuperclass();
String clazzName = clazz.getName();
/** Skip system classes, this just degrades performance. */
if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
clazz = null;
}
}
}

可见findState.clazz就是当前迭代的类,回到刚才的循环体内,进入getSubscriberInfo()方法看看:

private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
if (subscriberInfoIndexes != null) {
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}

findState.subscriberInfo在之前初始化findState时被赋值null
subscriberInfoIndexes来自之前的EventBusBuilder类中,回去看一下,可以发现 也是null
因此getSubscriberInfo()方法直接返回了null
而这两个变量后续一直没有改变,因此每次遍历时,该方法都是返回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();
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");
}
}
}

第5行获取了当前类中的所有方法,在catch块中执行了findState.skipSuperClasses = true;,根据之前的moveToSuperclass()方法可知此时findState.clazz将为null,之前的循环体将会退出。
第11至35行对找出的所有方法进行遍历,筛选出订阅者方法。
第13行对当前方法的修饰符进行判断,权限修饰符必须是public、且不能是staticabstract的。
第15行对当前方法的参数进行判断,参数只能是1个。
第17行判断当前方法是否有@Subscribe注解,有该注解才是订阅者方法。
第19行判断是否添加该订阅者方法,具体规则下面会讲。
第20至22行将该订阅者方法添加到findState.subscriberMethods列表,保存了5个参数,分别是methodeventType以及注解中的3个信息threadModeprioritysticky
现在看一下判断是否添加一个订阅者方法的规则:

boolean checkAdd(Method method, Class<?> eventType) {
// 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
// Usually a subscriber doesn't have methods listening to the same event type.
Object existing = anyMethodByEventType.put(eventType, method);
if (existing == null) {
return true;
}
else {
if (existing instanceof Method) {
if (!checkAddWithMethodSignature((Method) existing, eventType)) {
// Paranoia check
throw new IllegalStateException();
}

// Put any non-Method object to "consume" the existing Method
anyMethodByEventType.put(eventType, this);

}
return checkAddWithMethodSignature(method, eventType);
}
}

private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());

String methodKey = methodKeyBuilder.toString();
Class<?> methodClass = method.getDeclaringClass();
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
// Only add if not already found in a sub class
return true;
}
else {
// Revert the put, old class is further down the class hierarchy
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}

}

这里进行了双重校验,规则大致就是:
1. 同一个订阅者方法,子类中已经重写并添加的,父类中的方法不会被添加,还会抛错。
2. 同一个类中对同一事件多次订阅时,这些订阅都有效。
一般我们实际在用时,不会在子类中重写父类的订阅方法,同一个类中对同一事件只会订阅一次,因此不会出问题。
到这里,就完成了当前类的遍历过程,接着在父类们中重复此过程,找出所有的订阅者方法,直至到达系统源码,才退出循环。此时便返回这些找到的订阅者方法:

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
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;
}

刚才已经看到这些方法都保存在findState.subscriberMethods列表中,所以从该列表获取这些方法并返回。
现在回到之前的register()方法中,对找出的订阅者方法逐一进行订阅:

    // Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class<?> eventType = subscriberMethod.eventType;
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
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);
}
}

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;
}
}

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);
}
}
}

第4行很巧妙地利用subscribersubscriberMethod生成了一个Subscription对象,发送事件后调用订阅者方法将用到这些信息。
某一事件的所有订阅者方法保存在map类型变量subscriptionsByEventType中,key为事件类 Classvalue为泛型类CopyOnWriteArrayList<Subscription>
第16行获取了当前事件类的订阅者方法数大小,而第17至22行的代码就很有意思了,第18行表示只有迭代到最后或当前订阅比列表中订阅的优先级大(优先级来自于注解,如果双方都使用默认值,则优先级相同)时,才执行一次subscriptionsadd()方法,并退出循环体。来看一下add方法:

public synchronized void add(int index, E e) {
Object[] newElements = new Object[elements.length + 1];
System.arraycopy(elements, 0, newElements, 0, index);
newElements[index] = e;
System.arraycopy(elements, index, newElements, index + 1, elements.length - index);
elements = newElements;
}

该方法会在列表的index位置插入元素e,而index前的原有元素保持不变,index后的原有元素整体位置后移一位。
结合刚才的条件判断,刚才的第17至22行就是将同一事件的订阅者方法按优先级高低保存,到时候发送事件时优先级高的订阅者方法就能先收到事件。一般情况下优先级都是默认的,这时就会按注册时间先后保存。
第24至29行将当前注册类的所有事件保存在map类型变量typesBySubscriber中,这主要是为了注销unregister时用的,就不展开分析了。
第31行的subscriberMethod.sticky值也来自注解@Subscribe,默认为false,为简化分析,也不展开了。
到这里,EventBus.getDefault().register(this);这行代码就分析好了,还是有点多的。
其实我们只需要记住:某一事件的所有订阅者方法已经保存在map类型变量subscriptionsByEventType中了

EventBus.getDefault().post(new MessageEvent(“Hello everyone!”))

现在来分析一下EventBus.getDefault().post(new MessageEvent(“Hello everyone!”));这行代码。EventBus.getDefault()之前已经分析过了,我们从post()方法开始看:

    /** Posts the given event to the event bus. */
public void post(Object event) {
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;
}
}
}

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<Object>();
boolean isPosting;
boolean isMainThread;
Subscription subscription;
Object event;
boolean canceled;
}

这里逻辑还是比较清楚的,不用太多分析。
第8行判断post()方法的调用是否在主线程。
我们直接看第15行的方法:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class<?> eventClass = event.getClass();
boolean subscriptionFound = false;
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));
}
}
}

/** Looks up all Class objects including super classes and interfaces. Should also work for interfaces. */
private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
synchronized (eventTypesCache) {
List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class<?> clazz = eventClass;
while (clazz != null) {
eventTypes.add(clazz);
addInterfaces(eventTypes, clazz.getInterfaces());
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
}

/** Recurses through super interfaces. */
static void addInterfaces(List<Class<?>> eventTypes, Class<?>[] interfaces) {
for (Class<?> interfaceClass : interfaces) {
if (!eventTypes.contains(interfaceClass)) {
eventTypes.add(interfaceClass);
addInterfaces(eventTypes, interfaceClass.getInterfaces());
}
}
}

第4行eventInheritance值为true,也来自于EventBusBuilder
第5行获取当前事件类的所有父类和接口的Class,接着遍历获得这些Classsubscriptions并发送事件,只要发送成功了1次,当前事件便发送成功,整个流程结束。
现在看看第9行的postSingleEventForEventType()方法:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
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;
}

之前已经分析过,EventBus单例中的所有订阅者方法保存在subscriptionsByEventType中,第4行从中获取了当前事件的所有订阅者方法。再跟着看一下第12行的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);
}
}

可以看到,这里按注解@Subscribe指定的线程进行分支处理,并考虑当前线程是否与其一致。这里我们只分析最常见的情况:目标线程和当前线程都是主线程。那就看一下第8行:

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);
}
}

激动人心的时刻到了!!!
我们看到,这里用了反射,调用了我们定义的方法,subscription.subscriberMethod.method就是之前保存的方法,参数为event,调用发生在subscription.subscriber,也就是之前调用register(this)中的this,比如一个Activity
这样,EventBus.getDefault().post(new MessageEvent("Hello everyone!"));这行代码就分析完毕了,执行这行代码后最终将通过反射技术使订阅者方法得到执行。

通过整个流程的分析,现在我们就很清楚为什么按之前的3步操作后,Android组件之间的通讯就能实现!