最近正在学习EventBus源码,正好总结记录一下~
EventBus是一个针对Android优化的发布-订阅事件总线,它简化了应用程序内各个组件之间的通信,尤其是fragment和fragment之间的通信。优点是将发送者和接收者解耦,并且开销小,代码优雅。
一、EventBus的三要素
- Event:事件,可以是任意类型的对象;
- Subscriber:事件订阅者,事件处理方法可以随意取,但需要添加注解@Subscribe,并且要指定线程模型(默认POSTING);
- Publisher:事件发布者,可以在任意线程任意位置发送事件,直接调用post()即可;
EventBus的4种线程模型:
- POSTING(默认):发布事件和接收事件在同一个线程中,即事件在哪个线程中发布,事件处理就在哪个线程中执行;
- MAIN:事件处理会在UI线程中执行;
- ASYNC:事件不论在哪个线程中发布,事件处理都会在新建的子线程中执行;
- BACKGROUND:事件在UI线程中发布,事件处理会在新建的线程中执行,事件在子线程中发布,事件处理就会在发布事件的线程中执行;
二、源码解析
构造方法
一般我们会调用EventBus.getDefault()来获取EventBus实例,先来看下getDefault()代码:
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
上面代码是一个单例模式,采用了双重检查模式,如果defaultInstance为空,就new一个EventBus对象,来看下EventBus()里的代码:
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
public EventBus() {
this(DEFAULT_BUILDER);
}
this调用的是另一个构造方法:
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;
// builder.ignoreGeneratedIndex 是否忽略注解器生成的MyEventBusIndex
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 是否向上查找事件的父类
eventInheritance = builder.eventInheritance;
executorService = builder.executorService;
}
这个方法里初始化了一些属性,构造方法里传入了一个EventBusBuilder,而上面的DEFAULT_BUILDER就是一个默认的EventBusBuilder,使用这个方法可以对EventBus进行配置,使用自定义参数创建EventBus实例,也可以创建默认EventBus实例。
事件发送
获取到EventBus实例,我们调用post()方法来发送事件,来看post方法代码:
public void post(Object event) {
// PostingThreadState保存着事件队列和线程状态信息
PostingThreadState postingState = currentPostingThreadState.get();
// 获取事件队列,并将当前事件插入事件队列
List
首先从PostingThreadState取出事件队列,然后将当前事件插入队列,最后依次调用postSingleEvent()方法处理队列中事件,并移除该事件。进入postSingleEvent()代码:
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
Class> eventClass = event.getClass();
boolean subscriptionFound = false;
// eventInheritance表示是否向上查找事件的父类,在EventBusBuilder中声明,默认为true
if (eventInheritance) {
List> 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));
}
}
}
当eventInheritance为true时,通过lookupAllEventTypes()找到所有的父类事件并存到List中,遍历该List,调用postSingleEventForEventType()对事件进行处理。当eventInheritance为false时,直接调用postSingleEventForEventType()方法,显而易见,最后都走到这个postSingleEventForEventType()方法,我们来看源码:
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class> eventClass) {
CopyOnWriteArrayList subscriptions;
// 同步取出订阅对象集合
synchronized (this) {
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 遍历集合,将事件event和订阅对象subscription赋值给postingState
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,遍历subscriptions,将事件event和订阅对象subscription赋值给postingState,然后调用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 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);
}
}
这个方法里取出了订阅方法的线程模型,根据线程模型来分别处理:
- 如果线程模型是POSTING,就通过反射直接运行订阅的方法;
- 如果线程模型是MAIN,提交事件的是主线程,就通过反射直接运行订阅的方法,如果不是主线程,则通过mainThreadPoster将订阅事件添加到主线程队列里面;
- 如果线程模型是BACKGROUND,提交事件的是主线程,则通过backgroundPoster将订阅事件添加到子线程队列里面,如果不是主线程,就通过反射直接运行订阅的方法;
- 如果线程模型是ASYNC,就通过asyncPoster将订阅事件添加到子线程队列里面;
这就和我们上面提到的4种线程模型对上了~
事件注册
我们发送了事件,想要接收事件的话,需要先调用register()注册,源码如下:
public void register(Object subscriber) {
Class> subscriberClass = subscriber.getClass();
// 获取订阅者订阅方法集合
List subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
// 遍历订阅者方法集合,注册订阅者
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
register一共做了两件事:通过findSubscriberMethods()查找订阅者订阅方法集合subscriberMethods,以及遍历subscriberMethods集合,调用subscribe()进行订阅者的注册。
findSubscriberMethods()
我们先来看findSubscriberMethods()方法,源码如下:
List findSubscriberMethods(Class> subscriberClass) {
// 从缓存中获取订阅者方法集合
List subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
return subscriberMethods;
}
// ignoreGeneratedIndex默认false,在EventBusBuilder中声明,表示是否忽略注解器生成的MyEventBusIndex
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;
}
}
这个方法先从缓存中获取订阅者方法集合subscriberMethods,如果不为空,直接返回,如果为空就通过ignoreGeneratedIndex这个变量判断调用哪个方法,ignoreGeneratedIndex默认false,所以会调用findUsingInfo()方法获取订阅者方法集合subscriberMethods,拿到集合后将其放入缓存中。我们再看findUsingInfo()方法:
private List 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();
}
// 回收findState并返回订阅方法集合
return getMethodsAndRelease(findState);
}
首先调用prepareFindState()初始化findState,通过getSubscriberInfo()方法获取订阅者信息subscriberInfo,获取到信息后调用getSubscriberMethods()获取订阅方法相关信息,遍历相关信息,向订阅方法集合subscriberMethods中添加订阅方法对象subscriberMethod,最后调用getMethodsAndRelease()回收findState并返回订阅方法集合;如果没有获取到订阅者信息subscriberInfo,调用 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中
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");
}
}
}
调用getDeclaredMethods()通过反射获取订阅者中所有方法,遍历所有方法,根据方法类型、参数、注解找到订阅方法,将订阅方法保存到findState中。
subscribe()
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
Class> eventType = subscriberMethod.eventType;
// 创建订阅对象newSubscription
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// 根据事件类型eventType获取订阅对象集合subscriptions
CopyOnWriteArrayList subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions == null) {
subscriptions = new CopyOnWriteArrayList<>();
// 将订阅对象集合subscriptions保存到Map集合subscriptionsByEventType中
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) {
// 按照优先级将newSubscription插入订阅对象集合subscriptions中
subscriptions.add(i, newSubscription);
break;
}
}
// 通过订阅者subscriber获取事件类型集合subscribedEvents
List> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
// 将subscribedEvents存到Map集合typesBySubscriber中
typesBySubscriber.put(subscriber, subscribedEvents);
}
// 将事件类型eventType放入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).
Set, Object>> entries = stickyEvents.entrySet();
for (Map.Entry, 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()主要做了两件事:一件是将订阅对象集合subscriptions保存到Map集合subscriptionsByEventType中,将事件类型集合subscribedEvents保存到Map集合typesBySubscriber中;一件是对黏性事件的处理。
事件取消注册
取消注册调用unregister()方法,代码如下:
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
// 通过订阅者subscriber找到事件类型集合subscribedTypes
List> subscribedTypes = typesBySubscriber.get(subscriber);
if (subscribedTypes != null) {
for (Class> eventType : subscribedTypes) {
unsubscribeByEventType(subscriber, eventType);
}
// 将订阅者subscriber对应的事件类型从集合中移除
typesBySubscriber.remove(subscriber);
} else {
logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
先获取事件类型集合subscribedTypes,遍历该集合,调用unsubscribeByEventType()方法,并将订阅者subscriber对应的事件类型从集合subscribedTypes中移除。unsubscribeByEventType()代码:
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class> eventType) {
// 获取对应的订阅对象集合subscriptions
List subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
// 订阅对象的subscriber属性等于传进来的subscriber
if (subscription.subscriber == subscriber) {
subscription.active = false;
// 移除该订阅对象
subscriptions.remove(i);
i--;
size--;
}
}
}
}
到这,EventBus的源码基本完活啦~