这里从EventBus一个简单例子着手,逐步分析:
在订阅者类中添加订阅方法,往EventBus注册这个类。
public class MyEventSubscriber {
private WeakReference<Activity> mActivity;
public EventSubscriber(Activity activity) {
this.mActivity = new WeakReference<>(activity);
}
public void register() {
EventBus.getDefault().register(this);
}
public void unregister() {
EventBus.getDefault().unregister(this);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMyEvent(MyEvent event) {
//todo 处理事件
···
}
}
EventBus.getDefault().post(new MyEvent());
在这个例子中,定义类MyEventSubscriber,在类中添加响应通知事件的方法onMyEvent,在该方法上添加@Subscribe注解。需要订阅时通过register方法向EventBus注册,不需要订阅时通过unregister方法向EventBus解除注册。
有三种方式可以获取EventBus:
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
EventBus的构造方法中又通过DEFAULT_BUILDER初始化各成员变量:
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
public EventBus() {
this(DEFAULT_BUILDER);
}
2.通过直接new EventBus()
EventBus的构造方法为public,因此也可以直接new EventBus(),和defaultInstance互不影响。
3.通过EventBusBuilder构建
以上两种方式创建EventBus都使用DEFAULT_BUILDER的默认配置,还可以通过EventBusBuilder自行配置创建:
EventBus.builder()...build();
回到EventBus的构造方法,this(DEFAULT_BUILDER)传入默认builder,看看初始化哪些配置:
EventBus(EventBusBuilder builder) {
//缓存订阅方法,以发送的事件为key
subscriptionsByEventType = new HashMap<>();
//缓存发送的事件类型,以订阅者为key
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;
//查找和缓存订阅方法的工具类
//构造方法三个参数:1.索引类列表;2.严格方法验证,订阅方法必须只有一个参数,必须是public、非static、非abstract(默认false);3.即使存在生成的索引,也强制使用反射(默认false)
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
builder.strictMethodVerification, builder.ignoreGeneratedIndex);
//当反射调用订阅方法异常时是否打印log
logSubscriberExceptions = builder.logSubscriberExceptions;
//当未找到订阅方法时是否打印log
logNoSubscriberMessages = builder.logNoSubscriberMessages;
//当反射调用订阅方法异常时是否发送SubscriberExceptionEvent事件
sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
//当未找到订阅方法时是否发送NoSubscriberEvent事件
sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
//当反射调用订阅方法异常时是否抛出EventBusException异常
throwSubscriberException = builder.throwSubscriberException;
//是否支持事件继承
eventInheritance = builder.eventInheritance;
//用于在调用订阅方法时的线程调度
executorService = builder.executorService;
}
获取到EventBus对象后,调用它的register方法,将我们的订阅者MyEventSubscriber类注册进去。
订阅者必须在其中至少一个方法上添加@Subscribe注解,将方法标记为订阅方法。
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface Subscribe {
// 设置调用订阅方法时所在线程
ThreadMode threadMode() default ThreadMode.POSTING;
// 接收黏性事件(黏性事件即订阅者在事件发送之后再注册也能收到该事件)
boolean sticky() default false;
// 优先级,在相同threadMode中,优先级高的先收到事件
int priority() default 0;
}
接下来看看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);
}
}
}
接着看SubscriberMethodFinder的findSubscriberMethods方法:
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
// METHOD_CACHE是一个ConcurrentHashMap,缓存类中的订阅方法列表
List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
if (subscriberMethods != null) {
// 有缓存则直接返回缓存
return subscriberMethods;
}
// 是否忽略已生成的索引类,默认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 {
// 加入缓存,class作key,订阅方法列表作value
METHOD_CACHE.put(subscriberClass, subscriberMethods);
// 返回订阅方法列表
return subscriberMethods;
}
}
findSubscriberMethods中有两种方式查找订阅方法,依次分析:
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
// 创建FindState对象。先从对象缓存池中获取一个对象,然后移除缓存池中的对象;若对象缓存池中都为空,则new一个返回
FindState findState = prepareFindState();
// 初始化,FindState中保存订阅类的类型类
findState.initForSubscriber(subscriberClass);
// 遍历查找订阅方法,会将订阅方法保存在FindState中
while (findState.clazz != null) {
// 查找当前class
findUsingReflectionInSingleClass(findState);
// findState.clazz移到clazz的父类
findState.moveToSuperclass();
}
// 返回解析出的订阅方法,并释放临时缓存的资源
return getMethodsAndRelease(findState);
}
FindState对象主要负责临时保存找到的订阅方法,一个FindState对应一个订阅者类。先看它的initForSubscriber方法:
void initForSubscriber(Class<?> subscriberClass) {
// 保存了订阅类的类型类
this.subscriberClass = clazz = subscriberClass;
// 跳过父类开关默认false
skipSuperClasses = false;
// 索引类的基类
subscriberInfo = null;
}
查找指定class中的订阅方法findUsingReflectionInSingleClass:
private void findUsingReflectionInSingleClass(FindState findState) {
Method[] methods;
try {
// This is faster than getMethods, especially when subscribers are fat classes like Activities
// 获取当前class中的所有方法,
methods = findState.clazz.getDeclaredMethods();
} catch (Throwable th) {
// Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
// 发生异常,改为获取该类及其父类的所有public方法,并将跳过父类开关置为true
// getDeclaredMethods在部分Android4.x系统上,在Activity中重写生命周期方法,方法的修饰符没有一致时,根据类加载机制单一性原则,子类加载器不会再次加载父类加载器已经加载过的类,因此出现找不到该方法
methods = findState.clazz.getMethods();
findState.skipSuperClasses = true;
}
for (Method method : methods) {
// 获取method的修饰符
int modifiers = method.getModifiers();
// 位运算&,都为1结果为1否则为0
// 排除非public的方法和编译器添加的ACC_BRIDGE、ACC_SYNTHETIC方法
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
// 获取method的参数类型数组
Class<?>[] parameterTypes = method.getParameterTypes();
// 判断参数是否仅有一个
if (parameterTypes.length == 1) {
// 获取method上的@Subscribe注解
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
// 判断@Subscribe注解是否存在
if (subscribeAnnotation != null) {
// 拿到唯一的参数的类型
Class<?> eventType = parameterTypes[0];
// 校验是否添加过相同参数的方法
if (findState.checkAdd(method, eventType)) {
// 获取设置的线程模式
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 保存,SubscriberMethod对象记录解析出来的值,subscriberMethods为ArrayList
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");
}
}
}
看看FindState中的校验策略,在checkAdd方法:
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.
// 保存进anyMethodByEventType的HashMap集合
Object existing = anyMethodByEventType.put(eventType, method);
// 先判断是否保存了相同参数类型的method
if (existing == null) {
return true;
} else {
// 再判断是否保存了相同参数类型和相同方法名的method
// 判断之前保存的是否是一个method
if (existing instanceof Method) {
// 检查子类是否已经有同样的method
if (!checkAddWithMethodSignature((Method) existing, eventType)) {
// Paranoia check
// 目前没有发现哪些场景下会执行到这里
throw new IllegalStateException();
}
// Put any non-Method object to "consume" the existing Method
// 覆盖一个非Method的object,下次就会跳过这个if判断,直接执行下面语句
anyMethodByEventType.put(eventType, this);
}
return checkAddWithMethodSignature(method, eventType);
}
}
接着看checkAddWithMethodSignature:
private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
methodKeyBuilder.setLength(0);
methodKeyBuilder.append(method.getName());
methodKeyBuilder.append('>').append(eventType.getName());
// 拼接方法名和参数名作为key
String methodKey = methodKeyBuilder.toString();
// 获取method所在的类作为vulue
Class<?> methodClass = method.getDeclaringClass();
// 添加进subscriberClassByMethodKey,并获取旧值
Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
// 判断是否已经添加了相同方法名和参数名的method,若已添加,再判断已添加的method所在的类是否是当前待添加的method所在的类或其超类
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插入操作,返回失败
subscriberClassByMethodKey.put(methodKey, methodClassOld);
return false;
}
}
FindState中的校验策略主要就是检查是否存在相同方法名和参数名的method,如果存在则以最底层子类的为主。
回到SubscriberMethodFinder.findUsingReflectionInSingleClass方法中:
···
if (findState.checkAdd(method, eventType)) {
// 校验通过,创建SubscriberMethod对象保存订阅方法信息,保存进subscriberMethods中
ThreadMode threadMode = subscribeAnnotation.threadMode();
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
···
subscriberMethods为ArrayList,保存当前订阅者类及其超类中所有的订阅方法,SubscriberMethod对象记录具体订阅方法的信息:
public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
this.method = method; // 订阅方法
this.threadMode = threadMode; // 线程模式
this.eventType = eventType; // 参数类型
this.priority = priority; // 优先级
this.sticky = sticky; // 是否接收黏性事件
}
回到SubscriberMethodFinder.findUsingReflection方法中,执行完findUsingReflectionInSingleClass方法,就调用findState.moveToSuperclass,将class赋值父类:
void moveToSuperclass() {
// skipSuperClasses默认false,仅有当findUsingReflectionInSingleClass方法中通过clazz.getMethods()获取包含超类的方法时,置为true
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;
}
}
}
回到SubscriberMethodFinder.findUsingReflection方法,查找完了订阅者类及其超类的订阅方法,调用最后一句方法返回订阅方法信息列表:
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
···
return getMethodsAndRelease(findState);
}
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
// 取出findState中的订阅方法信息列表
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
// 释放findState中的资源,将findState的成员变量,ArrayList、HashMap全部清空
findState.recycle();
// 将findState放入对象缓存池
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;
}
以上是findUsingReflection方法的查找过程,接下来分析另一种查找方法。
private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
FindState findState = prepareFindState();
findState.initForSubscriber(subscriberClass);
// 和findUsingReflection方法相似,在while内有不同
while (findState.clazz != null) {
// 获取索引信息类。索引信息类中保存了订阅者类的类型类和订阅方法信息数组
findState.subscriberInfo = getSubscriberInfo(findState);
if (findState.subscriberInfo != null) {
// 存在索引信息类,则通过索引信息类获取订阅方法数组
// 索引信息类中的订阅方法信息数组中保存的是方法名,通过反射获取Method实例
SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
for (SubscriberMethod subscriberMethod : array) {
// 同findUsingReflection方法,对方法名和参数进行检查
if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
// 缓存订阅方法至subscriberMethods
findState.subscriberMethods.add(subscriberMethod);
}
}
} else {
// 若不存在索引信息类,则还是通过反射查找订阅方法
findUsingReflectionInSingleClass(findState);
}
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
看getSubscriberInfo方法:
private SubscriberInfo getSubscriberInfo(FindState findState) {
// 在EventBus3.0.0源码中,getSuperSubscriberInfo方法默认返回null
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
// 判断是否添加了索引(通过EventBusBuilder构建EventBus实例,由addIndex方法添加)
if (subscriberInfoIndexes != null) {
// 遍历添加的索引
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
// 从索引中根据订阅者类获取索引信息类。SubscriberInfoIndex会在静态代码块中初始化索引信息类,缓存在一个HashMap集合中
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
回到register方法中,通过subscriberMethodFinder获取到SubscriberMethod对象列表后,进行遍历,依次调用subscribe方法进行保存:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 获取订阅方法的参数类型类
Class<?> eventType = subscriberMethod.eventType;
// 创建Subscription对象保存订阅者对象和SubscriberMethod对象
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// subscriptionsByEventType是一个HashMap,事件参数类型作key,Subscription列表作value。根据事件参数类型来区分保存Subscription
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++) {
// 根据@Subscribe注解设置的优先级插入subscriptions中
if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
subscriptions.add(i, newSubscription);
break;
}
}
// 获取事件参数类型列表。typesBySubscriber是一个HashMap,订阅者类作key,事件参数类型列表作value。保存对应订阅者类中包含的所有事件参数类型
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).
// stickyEvents为ConcurrentHashMap,事件参数类型作key,发出的事件对象作value
Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
// 遍历stickyEvents,判断事件参数类型是否相同或是其超类,若是则取出事件分发
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);
}
}
}
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());
}
}
以上就是整个注册过程,先通过subscriberMethodFinder解析注册的订阅者类,拿到它的及父类的所有订阅方法,每个订阅方法用SubscriberMethod对象保存。之后将SubscriberMethod对应放进subscriptionsByEventType容器保存,将事件参数类型放进typesBySubscriber容器保存,若SubscriberMethod的method接收黏性事件,再取出缓存的黏性事件分发给它处理。
ps:注册时会检索当前类及父类,只要有一个@Subscribe的订阅方法就不会抛出异常;发出事件,订阅方法参数为该事件对象类及其父类的都会收到事件。
分析完注册方法,接着看看解除注册做了哪些操作。
/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
// 取出该订阅者类中包含的所有事件参数类型
List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
// 判断该订阅者是否是注册过的
if (subscribedTypes != null) {
for (Class<?> eventType : subscribedTypes) {
// 根据事件参数类型依次释放资源
unsubscribeByEventType(subscriber, eventType);
}
// 最后移除该订阅者
typesBySubscriber.remove(subscriber);
} else {
Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
}
}
/** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
// 通过事件参数类型获取Subscription列表
List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
if (subscriptions != null) {
int size = subscriptions.size();
for (int i = 0; i < size; i++) {
Subscription subscription = subscriptions.get(i);
// 判断是否是该订阅者类
if (subscription.subscriber == subscriber) {
// 将active标记为false
subscription.active = false;
// 从列表中移除
subscriptions.remove(i);
i--;
size--;
}
}
}
}
解除注册就是从缓存容器中移除该订阅者类相关的数据,先根据订阅者类获取所使用到的事件参数类型,然后再通过事件参数类型获取Subscription列表,将属于该订阅者类的Subscription的active置为false,并从缓存中移除。
通过post方法发送普通事件,postSticky方法发送黏性事件。
发送黏性事件:
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发送
post(event);
}
发送黏性事件和普通事件的区别就是,事件对象需要保存进stickyEvents中。
接下来分析post方法:
public void post(Object event) {
// 获取当前线程的PostingThreadState对象。currentPostingThreadState是一个ThreadLocal,postingState储存了分发事件过程中的状态以及相关对象信息
PostingThreadState postingState = currentPostingThreadState.get();
// 从postingState中获取事件队列,将本次发送的事件添加进去
List<Object> eventQueue = postingState.eventQueue;
eventQueue.add(event);
// 判断是否已分发
if (!postingState.isPosting) {
// 通过Looper来判断是否是在主线程
postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
// isPosting标记为true
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;
}
}
}
post中使用PostingThreadState记录当前线程的分发状态:
final static class PostingThreadState {
final List<Object> eventQueue = new ArrayList<Object>(); // 存储待分发的事件
boolean isPosting; // 标记是否在分发中
boolean isMainThread; // 标记是否在主线程
Subscription subscription; // 标记正在调用的订阅方法
Object event; // 标记传入给正在调用的订阅方法的事件
boolean canceled; // 标记是否被终止
}
下面分析postSingleEvent方法:
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);
// 使用或等,有一次返回true即可
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) {
// 发送NoSubscriberEvent事件
post(new NoSubscriberEvent(this, event));
}
}
}
postSingleEvent中通过lookupAllEventTypes获取事件的超类和接口:
private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
synchronized (eventTypesCache) {
// 从缓存中获取事件类型列表。eventTypesCache是一个HashMap,待发送事件类型作key,事件类型列表为value,存储了eventClass本身及其超类和接口
List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
if (eventTypes == null) {
eventTypes = new ArrayList<>();
Class<?> clazz = eventClass;
// 不断循环直到顶层父类
while (clazz != null) {
// 先添加自身
eventTypes.add(clazz);
// addInterfaces方法是递归调用,添加clazz的所有接口和接口的接口
addInterfaces(eventTypes, clazz.getInterfaces());
// 提至父类
clazz = clazz.getSuperclass();
}
eventTypesCache.put(eventClass, eventTypes);
}
return eventTypes;
}
}
接下来看postSingleEventForEventType方法:
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 获取事件参数类型对应的所有Subscription
subscriptions = subscriptionsByEventType.get(eventClass);
}
if (subscriptions != null && !subscriptions.isEmpty()) {
// 遍历Subscription列表
for (Subscription subscription : subscriptions) {
// 记录要分发的事件
postingState.event = event;
// 记录将要发送的subscription
postingState.subscription = subscription;
boolean aborted = false;
try {
// 将事件发送给subscription中保存的订阅方法
postToSubscription(subscription, event, postingState.isMainThread);
// 若在订阅方法中终止了事件分发,如调用了cancelEventDelivery分发,canceled会置为true
aborted = postingState.canceled;
} finally {
// 标记字段复位
postingState.event = null;
postingState.subscription = null;
postingState.canceled = false;
}
// 若终止,则结束循环,后面的subscription中的订阅方法将不执行
if (aborted) {
break;
}
}
return true;
}
// 没有对应的Subscription返回false
return false;
}
真正开始发送事件的postToSubscription方法,在上文的注册订阅中,黏性事件也是调用到这个分发,接下来分析它:
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
// 判断线程模式
switch (subscription.subscriberMethod.threadMode) {
case POSTING:
// 在当前线程调用订阅方法
invokeSubscriber(subscription, event);
break;
case MAIN:
// 若当前在主线程就直接调用订阅方法,否则通过mainThreadPoster在主线程调用
if (isMainThread) {
invokeSubscriber(subscription, event);
} else {
mainThreadPoster.enqueue(subscription, event);
}
break;
case BACKGROUND:
// 若当前在非主线程,直接调用订阅方法,否则通过backgroundPoster在非主线程调用
if (isMainThread) {
backgroundPoster.enqueue(subscription, event);
} else {
invokeSubscriber(subscription, event);
}
break;
case ASYNC:
// 统统交由asyncPoster在子线程调用订阅方法
asyncPoster.enqueue(subscription, event);
break;
default:
throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
}
}
先看直接发送事件给订阅方法invokeSubscriber:
void invokeSubscriber(Subscription subscription, Object event) {
try {
// 通过反射调用订阅方法
subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
} catch (InvocationTargetException e) {
// 处理异常类型,打印日志或抛出异常或发送SubscriberExceptionEvent
handleSubscriberException(subscription, event, e.getCause());
} catch (IllegalAccessException e) {
throw new IllegalStateException("Unexpected exception", e);
}
}
mainThreadPoster、backgroundPoster、asyncPoster都是在EventBus初始化时创建,下面逐个分析:
mainThreadPoster是Handler的子类,创建时传入了mainLooper。
HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
super(looper); // mainLooper
this.eventBus = eventBus; // EventBus实例
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage; // 在handleMessage中执行的最大时间,这里是10ms
queue = new PendingPostQueue(); // 链表,存储事件队列,节点为PendingPost对象
}
将事件入队:
void enqueue(Subscription subscription, Object event) {
// 从对象缓存池中取出PendingPost对象,PendingPost中保存subscription、event
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
// 将PendingPost添加至链表尾部
queue.enqueue(pendingPost);
// 判断标记是否在处理分发
if (!handlerActive) {
handlerActive = true;
// handler发送消息,最终在主线程handleMessage中处理事件分发
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
处理事件发送给订阅方法:
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
// 遍历事件队列
while (true) {
// 取出链表头节点
PendingPost pendingPost = queue.poll();
// 双重检查
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
// 若已没有事件,则处理分发事件标记false,然后退出
handlerActive = false;
return;
}
}
}
// 利用反射调用订阅方法
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
// 判断本次handleMessage执行时间是否达到设置的10ms
if (timeInMethod >= maxMillisInsideHandleMessage) {
// 再次发送message,并判断looper是否已退出
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
可以看出mainThreadPoster的处理过程,先将事件加入队列,然后通过Handler切换至主线程,最后在handleMessage中不断取出事件发送给订阅方法处理。
backgroundPoster继承自Runnable,实现了run方法。内部同样使用PendingPostQueue保存事件。
public void enqueue(Subscription subscription, Object event) {
// 同样获取PendingPost对象
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
// 将事件入队
queue.enqueue(pendingPost);
// 判断是否在运行标记
if (!executorRunning) {
executorRunning = true;
// 交给线程池切换至子线程运行
eventBus.getExecutorService().execute(this);
}
}
}
@Override
public void run() {
try {
try {
// 遍历队列
while (true) {
// 取出链表头节点
PendingPost pendingPost = queue.poll(1000);
// 双重检查
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
// 已经没有事件,标记复位,退出
executorRunning = false;
return;
}
}
}
// 反射调用订阅方法
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
// 执行结束或捕获异常,标记复位
executorRunning = false;
}
}
backgroundPoster处理过程,同样将事件加入队列,然后利用线程池切换到子线程,不断从链表取出事件发送给订阅方法处理。
asyncPoster继承自Runnable,实现了run方法,内部同样有一个PendingPostQueue。
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
// 事件入队
queue.enqueue(pendingPost);
// 交给线程池切换至子线程运行
eventBus.getExecutorService().execute(this);
}
@Override
public void run() {
// 取出头节点
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
// 发送给订阅方法执行
eventBus.invokeSubscriber(pendingPost);
}
asyncPoster和backgroundPoster类似,区别就是asyncPoster一次处理一个事件,而backgroundPoster会遍历队列所有事件,可以保证当前队列中的所有事件在一个子线程中处理。
到这里就分析完了EventBus的初始化、注册、解注册和事件发送流程。EventBus3.0最大的新特性Subscriber Index,后面再分析。