第三方库探究|What(EventBus的核心竟然只是这两个Map?)

简单介绍一下EventBus 其实EventBus大家都很熟悉了,就不过多去说它了。通常我们叫它事件总线,其实它更像是广播,观察者模式,一方发送消息多方接收。在EventBus的创建订阅过程中,最重要的就是有两个关键的Map,这两个键值对里面存储了我们定义的订阅方法和相关的类,那到底是具体是怎么操作的呢,来源码一探究竟。

下面的代码基于EventBus3.1.1
创建和订阅消息 注册
EventBus的注册很简单,
@Override public void onStart() { super.onStart(); EventBus.getDefault().register(this); } @Override public void onStop() { super.onStop(); EventBus.getDefault().unregister(this); }

这里一定要记住在onStop中注销,避免在Activity关闭后还跟EventBus有联系,然后造成内存泄漏。
接下来进入到方法中看一看:
单例模式
EventBus.getDefault
public static EventBus getDefault() { if (defaultInstance == null) { synchronized (EventBus.class) { if (defaultInstance == null) { defaultInstance = new EventBus(); } } } return defaultInstance; }

这个方法很简单,就是双重校验单例,继续看register方法:
register方法
EventBus.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中,传入的参数名为subscriber,意思就是订阅者,类型为Object。在这个方法里有个List的列表,这个SubscriberMethod是什么呢?
public class SubscriberMethod { final Method method; //对应的方法 final ThreadMode threadMode; //线程模式 final Class eventType; //消息类型 final int priority; //优先级 final boolean sticky; //是否支持粘性 /** Used for efficient comparison */ String methodString; //用于equal对比 }

其实这个类就保存了我们订阅者里面定义的方法里面的所有信息。
线程模式
其中threadMode的定义如下:
  • ThreadMode.POSTING:默认的线程模式,在那个线程发送事件就在对应线程处理事件,避免了线程切换,效率高。
  • ThreadMode.MAIN:如在主线程(UI线程)发送事件,则直接在主线程处理事件;如果在子线程发送事件,则先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
  • 【第三方库探究|What(EventBus的核心竟然只是这两个Map?)】ThreadMode.MAIN_ORDERED:无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。
  • ThreadMode.BACKGROUND:如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件;如果在子线程发送事件,则直接在发送事件的线程处理事件。
  • ThreadMode.ASYNC:无论在那个线程发送事件,都将事件入队列,然后通过线程池处理。
所以在register方法中的这个列表其实就是当前我们这个订阅者类包含所有的接收方法。这里通过subscriberMethodFinder.findSubscriberMethods(subscriberClass)方法获取:
查找订阅事件的方法(接收消息的方法)
SubscriberMethodFinder findSubscriberMethods
private static final Map, List>> METHOD_CACHE = new ConcurrentHashMap<>(); List> findSubscriberMethods(Class subscriberClass) { List> 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; } }

这里我们注意到有一个ignoreGeneratedIndex参数,这个属性的值是在构造方法中获取的
subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes, builder.strictMethodVerification, builder.ignoreGeneratedIndex);

/** Forces the use of reflection even if there's a generated index (default: false). */ public EventBusBuilder ignoreGeneratedIndex(boolean ignoreGeneratedIndex) { this.ignoreGeneratedIndex = ignoreGeneratedIndex; return this; }

从官方的注释可以看出,这里默认值是false,所以是调用findUsingInfo方法:
private List> findUsingInfo(Class subscriberClass) { FindState findState = prepareFindState(); findState.initForSubscriber(subscriberClass); //初始化查找辅助类 while (findState.clazz != null) {//这里就是我们register的类 findState.subscriberInfo = getSubscriberInfo(findState); if (findState.subscriberInfo != null) {//初始状态为空,所以执行else 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); //释放资源 }

FindState是查找辅助类,里面存储了关于查找到的订阅方法信息和相关类的信息:
static class FindState { final List> subscriberMethods = new ArrayList<>(); //订阅的方法 final Map anyMethodByEventType = new HashMap<>(); //通过消息类型获取方法 final Map, Class> subscriberClassByMethodKey = new HashMap<>(); //通过方法获取订阅的类 final StringBuilder methodKeyBuilder = new StringBuilder(128); Class subscriberClass; Class clazz; boolean skipSuperClasses; SubscriberInfo subscriberInfo; }

在这里会执行else里面的findUsingReflectionInSingleClass方法,通过反射来查找订阅方法
SubscriberMethodFinder 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) {//public,非abstract、static Class[] parameterTypes = method.getParameterTypes(); //获取参数类型 if (parameterTypes.length == 1) {//只能有一个参数 Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); //获取Subscribe注解 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"); } } }

整个的过程就是遍历所有的方法,然后判断有Subscribe注解的方法,然后将方法的信息加到数组当中。在查找完毕之后,接下来回到register方法
public void register(Object subscriber) { Class subscriberClass = subscriber.getClass(); List> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); synchronized (this) { for (SubscriberMethod subscriberMethod : subscriberMethods) { subscribe(subscriber, subscriberMethod); } } }

循环订阅 拿到我们刚才的所有订阅方法的数组,然后在循环中执行subscribe方法,这个方法执行订阅操作:
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { Class eventType = subscriberMethod.eventType; //获取我们自定义的消息类型 Subscription newSubscription = new Subscription(subscriber, subscriberMethod); //新建一个订阅类,这个类包含了订阅的类和方法两个属性 //subscriptionsByEventType是以eventType为key,Subscription数组为value的map CopyOnWriteArrayList> subscriptions = subscriptionsByEventType.get(eventType); if (subscriptions == null) {//为空的话创建数组,并加入到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; } } //typesBySubscriber是以对象为key,订阅的方法的数组为value的map List> 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). 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); } } }


其实EventBus的register方法的内部具体做的事情很简单,总的来说就是两步:
  1. 通过反射查找我们使用了Subscribe注解的订阅方法
  2. 循环遍历找到的方法,然后加到关键的两个map中(subscriptionsByEventType和typesBySubscriber)
subscriptionsByEventType:以eventType为key,Subscription数组为value typesBySubscriber:以对象为key,订阅的方法的数组为value 第三方库探究|What(EventBus的核心竟然只是这两个Map?)
文章图片
聊技术 聊电影 聊人生 什么都聊的公众号

    推荐阅读