一文彻底搞懂EventBus3.0事件总线框架原理

开发 前端
EventBus 是一款在 Android 开发中使用的发布/订阅事件总线框架,基于观察者模式,将事件的接收者和发送者分开,简化了组件之间的通信,使用简单、效率高、体积小。

[[412323]]

前沿小记

1、关于架构师学习的知识点很多,学到手才是自己的;

2、之前发过文章有自定义注解、设计模式、反射、多线程、组件化等;

3、实际开发中EventBus事件总线用到的很多,今天我们就解析下原理和用到的知识点;

4、在eventbus源码中可以学习到很多的知识点如下:

单例模式,而且是双重校验的单例,确保在不同线程中也只存在一个EvenBus的实例;

观察者模式:定义了对象之间的一对多依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新;

自定义注解等等。

一、EventBus介绍

1、什么是EventBus

  • 由greenrobot 组织贡献(该组织还贡献了greenDAO),一个Android事件发布/订阅轻量级框架,通过解耦发布者和订阅者简化Android事件传递;
  • EventBus可以代替Android传统的Intent,Handler,Broadcast或接口函数,在Fragment,Activity,Service线程之间传递数据,执行方法;
  • EventBus 是一款在 Android 开发中使用的发布/订阅事件总线框架,基于观察者模式,将事件的接收者和发送者分开,简化了组件之间的通信,使用简单、效率高、体积小 ;

2、eventbus功能和优势

  • 通过解耦发布者和订阅者简化Android事件传递;
  • 用于线程间的通讯代替handler或用于组件间的通讯代替Intent;
  • 简化了组件间的通讯;
  • 分离了事件的发送者和接受者;
  • 在Activity、Fragment和线程中表现良好;
  • 避免了复杂的和易错的依赖关系和生命周期问题;
  • 使得代码更简洁,性能更好;

二、EventBus原理


EventBus 背后的实现原理主要包括如下几个方面的内容:

  • Subscribe注解
  • 注册事件订阅方法
  • 取消注册
  • 发送事件
  • 事件处理

1、Subscribe注解

EventBus3.0 开始用Subscribe注解配置事件订阅方法

  1. @Subscribe 
  2. public void handleEvent(String event) { 
  3.     // do something 

具体看下Subscribe注解的实现:

  1. @Documented 
  2. @Retention(RetentionPolicy.RUNTIME) 
  3. @Target({ElementType.METHOD}) 
  4. public @interface Subscribe { 
  5.     // 指定事件订阅方法的线程模式,即在那个线程执行事件订阅方法处理事件,默认为POSTING 
  6.     ThreadMode threadMode() default ThreadMode.POSTING; 
  7.     // 是否支持粘性事件,默认为false 
  8.     boolean sticky() default false
  9.     // 指定事件订阅方法的优先级,默认为0,如果多个事件订阅方法可以接收相同事件的,则优先级高的先接收到事件 
  10.     int priority() default 0; 

在使用Subscribe注解时可以根据需求指定threadMode、sticky、priority三个属性;

其中threadMode属性有如下几个可选值:

  • ThreadMode.POSTING,默认的线程模式,在那个线程发送事件就在对应线程处理事件,避免了线程切换,效率高;
  • ThreadMode.MAIN,如在主线程(UI线程)发送事件,则直接在主线程处理事件;如果在子线程发送事件,则先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件;
  • ThreadMode.MAIN_ORDERED,无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件;
  • ThreadMode.BACKGROUND,如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件;如果在子线程发送事件,则直接在发送事件的线程处理事件;
  • ThreadMode.ASYNC,无论在那个线程发送事件,都将事件入队列,然后通过线程池处理;

2、注册事件订阅方法

注册事件的方式如下:

  1. EventBus.getDefault().register(this); 

其中getDefault()是一个单例方法,保证当前只有一个EventBus实例:

  1. public static EventBus getDefault() { 
  2.         if (defaultInstance == null) { 
  3.             synchronized (EventBus.class) { 
  4.                 if (defaultInstance == null) { 
  5.                     defaultInstance = new EventBus(); 
  6.                 } 
  7.             } 
  8.         } 
  9.         return defaultInstance; 
  10.     } 

在这里又调用了EventBus的构造函数来完成它相关属性的初始化:

  1. public EventBus() { 
  2.         this(DEFAULT_BUILDER); 
  3.     } 
  1. EventBus(EventBusBuilder builder) { 
  2.         logger = builder.getLogger(); 
  3.         subscriptionsByEventType = new HashMap<>(); 
  4.         typesBySubscriber = new HashMap<>(); 
  5.         stickyEvents = new ConcurrentHashMap<>(); 
  6.         mainThreadSupport = builder.getMainThreadSupport(); 
  7.         mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null
  8.         backgroundPoster = new BackgroundPoster(this); 
  9.         asyncPoster = new AsyncPoster(this); 
  10.         indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0; 
  11.         subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes, 
  12.                 builder.strictMethodVerification, builder.ignoreGeneratedIndex); 
  13.         logSubscriberExceptions = builder.logSubscriberExceptions; 
  14.         logNoSubscriberMessages = builder.logNoSubscriberMessages; 
  15.         sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent; 
  16.         sendNoSubscriberEvent = builder.sendNoSubscriberEvent; 
  17.         throwSubscriberException = builder.throwSubscriberException; 
  18.         eventInheritance = builder.eventInheritance; 
  19.         executorService = builder.executorService; 
  20.     } 

DEFAULT_BUILDER就是一个默认的EventBusBuilder:

  1. private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder(); 

有了EventBus的实例就可以进行注册了:

  1. public void register(Object subscriber) { 
  2.         // 得到当前要注册类的Class对象 
  3.         Class<?> subscriberClass = subscriber.getClass(); 
  4.         // 根据Class查找当前类中订阅了事件的方法集合,即使用了Subscribe注解、有public修饰符、一个参数的方法 
  5.         // SubscriberMethod类主要封装了符合条件方法的相关信息: 
  6.         // Method对象、线程模式、事件类型、优先级、是否是粘性事等 
  7.         List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); 
  8.         synchronized (this) { 
  9.             // 循环遍历订阅了事件的方法集合,以完成注册 
  10.             for (SubscriberMethod subscriberMethod : subscriberMethods) { 
  11.                 subscribe(subscriber, subscriberMethod); 
  12.             } 
  13.         } 
  14.     } 

可以看到register()方法主要分为查找和注册两部分,首先来看查找的过程,从findSubscriberMethods()开始:

  1. List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) { 
  2.         // METHOD_CACHE是一个ConcurrentHashMap,直接保存了subscriberClass和对应SubscriberMethod的集合,以提高注册效率,赋值重复查找。 
  3.         List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass); 
  4.         if (subscriberMethods != null) { 
  5.             return subscriberMethods; 
  6.         } 
  7.         // 由于使用了默认的EventBusBuilder,则ignoreGeneratedIndex属性默认为false,即是否忽略注解生成器 
  8.         if (ignoreGeneratedIndex) { 
  9.             subscriberMethods = findUsingReflection(subscriberClass); 
  10.         } else { 
  11.             subscriberMethods = findUsingInfo(subscriberClass); 
  12.         } 
  13.         // 如果对应类中没有符合条件的方法,则抛出异常 
  14.         if (subscriberMethods.isEmpty()) { 
  15.             throw new EventBusException("Subscriber " + subscriberClass 
  16.                     + " and its super classes have no public methods with the @Subscribe annotation"); 
  17.         } else { 
  18.             // 保存查找到的订阅事件的方法 
  19.             METHOD_CACHE.put(subscriberClass, subscriberMethods); 
  20.             return subscriberMethods; 
  21.         } 
  22.     } 

findSubscriberMethods()流程很清晰,即先从缓存中查找,如果找到则直接返回,否则去做下一步的查找过程,然后缓存查找到的集合,根据上边的注释可知findUsingInfo()方法会被调用:

  1. private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) { 
  2.         FindState findState = prepareFindState(); 
  3.         findState.initForSubscriber(subscriberClass); 
  4.         // 初始状态下findState.clazz就是subscriberClass 
  5.         while (findState.clazz != null) { 
  6.             findState.subscriberInfo = getSubscriberInfo(findState); 
  7.             // 条件不成立 
  8.             if (findState.subscriberInfo != null) { 
  9.                 SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods(); 
  10.                 for (SubscriberMethod subscriberMethod : array) { 
  11.                     if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) { 
  12.                         findState.subscriberMethods.add(subscriberMethod); 
  13.                     } 
  14.                 } 
  15.             } else { 
  16.                 // 通过反射查找订阅事件的方法 
  17.                 findUsingReflectionInSingleClass(findState); 
  18.             } 
  19.             // 修改findState.clazz为subscriberClass的父类Class,即需要遍历父类 
  20.             findState.moveToSuperclass(); 
  21.         } 
  22.         // 查找到的方法保存在了FindState实例的subscriberMethods集合中。 
  23.         // 使用subscriberMethods构建一个新的List<SubscriberMethod> 
  24.         // 释放掉findState 
  25.         return getMethodsAndRelease(findState); 
  26.     } 

findUsingInfo()方法会在当前要注册的类以及其父类中查找订阅事件的方法,这里出现了一个FindState类,它是SubscriberMethodFinder的内部类,用来辅助查找订阅事件的方法,具体的查找过程在findUsingReflectionInSingleClass()方法,它主要通过反射查找订阅事件的方法:

  1. private void findUsingReflectionInSingleClass(FindState findState) { 
  2.         Method[] methods; 
  3.         try { 
  4.             // This is faster than getMethods, especially when subscribers are fat classes like Activities 
  5.             methods = findState.clazz.getDeclaredMethods(); 
  6.         } catch (Throwable th) { 
  7.             // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149 
  8.             methods = findState.clazz.getMethods(); 
  9.             findState.skipSuperClasses = true
  10.         } 
  11.         // 循环遍历当前类的方法,筛选出符合条件的 
  12.         for (Method method : methods) { 
  13.             // 获得方法的修饰符 
  14.             int modifiers = method.getModifiers(); 
  15.             // 如果是public类型,但非abstract、static等 
  16.             if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) { 
  17.                 // 获得当前方法所有参数的类型 
  18.                 Class<?>[] parameterTypes = method.getParameterTypes(); 
  19.                 // 如果当前方法只有一个参数 
  20.                 if (parameterTypes.length == 1) { 
  21.                     Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); 
  22.                     // 如果当前方法使用了Subscribe注解 
  23.                     if (subscribeAnnotation != null) { 
  24.                         // 得到该参数的类型 
  25.                         Class<?> eventType = parameterTypes[0]; 
  26.                         // checkAdd()方法用来判断FindState的anyMethodByEventType map是否已经添加过以当前eventType为key的键值对,没添加过则返回true 
  27.                         if (findState.checkAdd(method, eventType)) { 
  28.                              // 得到Subscribe注解的threadMode属性值,即线程模式 
  29.                             ThreadMode threadMode = subscribeAnnotation.threadMode(); 
  30.                             // 创建一个SubscriberMethod对象,并添加到subscriberMethods集合 
  31.                             findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode, 
  32.                                     subscribeAnnotation.priority(), subscribeAnnotation.sticky())); 
  33.                         } 
  34.                     } 
  35.                 } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) { 
  36.                     String methodName = method.getDeclaringClass().getName() + "." + method.getName(); 
  37.                     throw new EventBusException("@Subscribe method " + methodName + 
  38.                             "must have exactly 1 parameter but has " + parameterTypes.length); 
  39.                 } 
  40.             } else if (strictMethodVerification && method.isAnnotationPresent(Subscribe.class)) { 
  41.                 String methodName = method.getDeclaringClass().getName() + "." + method.getName(); 
  42.                 throw new EventBusException(methodName + 
  43.                         " is a illegal @Subscribe method: must be public, non-static, and non-abstract"); 
  44.             } 
  45.         } 
  46.     } 

到此register()方法中findSubscriberMethods()流程就分析完了,我们已经找到了当前注册类及其父类中订阅事件的方法的集合。接下来分析具体的注册流程,即register()中的subscribe()方法:

  1. private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) { 
  2.         // 得到当前订阅了事件的方法的参数类型 
  3.         Class<?> eventType = subscriberMethod.eventType; 
  4.         // Subscription类保存了要注册的类对象以及当前的subscriberMethod 
  5.         Subscription newSubscription = new Subscription(subscriber, subscriberMethod); 
  6.         // subscriptionsByEventType是一个HashMap,保存了以eventType为key,Subscription对象集合为value的键值对 
  7.         // 先查找subscriptionsByEventType是否存在以当前eventType为key的值 
  8.         CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType); 
  9.         // 如果不存在,则创建一个subscriptions,并保存到subscriptionsByEventType 
  10.         if (subscriptions == null) { 
  11.             subscriptions = new CopyOnWriteArrayList<>(); 
  12.             subscriptionsByEventType.put(eventType, subscriptions); 
  13.         } else { 
  14.             if (subscriptions.contains(newSubscription)) { 
  15.                 throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " 
  16.                         + eventType); 
  17.             } 
  18.         } 
  19.         // 添加上边创建的newSubscription对象到subscriptions中 
  20.         int size = subscriptions.size(); 
  21.         for (int i = 0; i <= size; i++) { 
  22.             if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) { 
  23.                 subscriptions.add(i, newSubscription); 
  24.                 break; 
  25.             } 
  26.         } 
  27.         // typesBySubscribere也是一个HashMap,保存了以当前要注册类的对象为key,注册类中订阅事件的方法的参数类型的集合为value的键值对 
  28.         // 查找是否存在对应的参数类型集合 
  29.         List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); 
  30.         // 不存在则创建一个subscribedEvents,并保存到typesBySubscriber 
  31.         if (subscribedEvents == null) { 
  32.             subscribedEvents = new ArrayList<>(); 
  33.             typesBySubscriber.put(subscriber, subscribedEvents); 
  34.         } 
  35.         // 保存当前订阅了事件的方法的参数类型 
  36.         subscribedEvents.add(eventType); 
  37.         // 粘性事件相关的,后边具体分析 
  38.         if (subscriberMethod.sticky) { 
  39.             if (eventInheritance) { 
  40.                 // Existing sticky events of all subclasses of eventType have to be considered. 
  41.                 // Note: Iterating over all events may be inefficient with lots of sticky events, 
  42.                 // thus data structure should be changed to allow a more efficient lookup 
  43.                 // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>). 
  44.                 Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet(); 
  45.                 for (Map.Entry<Class<?>, Object> entry : entries) { 
  46.                     Class<?> candidateEventType = entry.getKey(); 
  47.                     if (eventType.isAssignableFrom(candidateEventType)) { 
  48.                         Object stickyEvent = entry.getValue(); 
  49.                         checkPostStickyEventToSubscription(newSubscription, stickyEvent); 
  50.                     } 
  51.                 } 
  52.             } else { 
  53.                 Object stickyEvent = stickyEvents.get(eventType); 
  54.                 checkPostStickyEventToSubscription(newSubscription, stickyEvent); 
  55.             } 
  56.         } 
  57.     } 

这就是注册的核心流程,所以subscribe()方法主要是得到了subscriptionsByEventType、typesBySubscriber两个 HashMap。我们在发送事件的时候要用到subscriptionsByEventType,完成事件的处理。当取消 EventBus 注册的时候要用到typesBySubscriber、subscriptionsByEventType,完成相关资源的释放;

3、取消注册

EventBus 取消注册:

  1. EventBus.getDefault().unregister(this); 

核心的方法就是unregister():

  1. public synchronized void unregister(Object subscriber) { 
  2.         // 得到当前注册类对象 对应的 订阅事件方法的参数类型 的集合 
  3.         List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber); 
  4.         if (subscribedTypes != null) { 
  5.             // 遍历参数类型集合,释放之前缓存的当前类中的Subscription 
  6.             for (Class<?> eventType : subscribedTypes) { 
  7.                 unsubscribeByEventType(subscriber, eventType); 
  8.             } 
  9.             // 删除以subscriber为key的键值对 
  10.             typesBySubscriber.remove(subscriber); 
  11.         } else { 
  12.             logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass()); 
  13.         } 
  14.     } 
  15. 继续看unsubscribeByEventType()方法: 
  16. private void unsubscribeByEventType(Object subscriber, Class<?> eventType) { 
  17.         // 得到当前参数类型对应的Subscription集合 
  18.         List<Subscription> subscriptions = subscriptionsByEventType.get(eventType); 
  19.         if (subscriptions != null) { 
  20.             int size = subscriptions.size(); 
  21.             // 遍历Subscription集合 
  22.             for (int i = 0; i < size; i++) { 
  23.                 Subscription subscription = subscriptions.get(i); 
  24.                 // 如果当前subscription对象对应的注册类对象 和 要取消注册的注册类对象相同,则删除当前subscription对象 
  25.                 if (subscription.subscriber == subscriber) { 
  26.                     subscription.active = false
  27.                     subscriptions.remove(i); 
  28.                     i--; 
  29.                     size--; 
  30.                 } 
  31.             } 
  32.         } 
  33.     } 

所以在unregister()方法中,释放了typesBySubscriber、subscriptionsByEventType中缓存的资源。

4、事件通知

发送一个事件的时候,我们可以通过如下方式

  1. EventBus.getDefault().post("Hello World!"

通过post()方法完成的:

  1. public void post(Object event) { 
  2.         // currentPostingThreadState是一个PostingThreadState类型的ThreadLocal 
  3.         // PostingThreadState类保存了事件队列和线程模式等信息 
  4.         PostingThreadState postingState = currentPostingThreadState.get(); 
  5.         List<Object> eventQueue = postingState.eventQueue; 
  6.         // 将要发送的事件添加到事件队列 
  7.         eventQueue.add(event); 
  8.         // isPosting默认为false 
  9.         if (!postingState.isPosting) { 
  10.             // 是否为主线程 
  11.             postingState.isMainThread = isMainThread(); 
  12.             postingState.isPosting = true
  13.             if (postingState.canceled) { 
  14.                 throw new EventBusException("Internal error. Abort state was not reset"); 
  15.             } 
  16.             try { 
  17.                 // 遍历事件队列 
  18.                 while (!eventQueue.isEmpty()) { 
  19.                     // 发送单个事件 
  20.                     // eventQueue.remove(0),从事件队列移除事件 
  21.                     postSingleEvent(eventQueue.remove(0), postingState); 
  22.                 } 
  23.             } finally { 
  24.                 postingState.isPosting = false
  25.                 postingState.isMainThread = false
  26.             } 
  27.         } 
  28.     } 

所以post()方法先将发送的事件保存的事件队列,然后通过循环出队列,将事件交给postSingleEvent()方法处理

  1. private void postSingleEvent(Object event, PostingThreadState postingState) throws Error { 
  2.         Class<?> eventClass = event.getClass(); 
  3.         boolean subscriptionFound = false
  4.         // eventInheritance默认为true,表示是否向上查找事件的父类 
  5.         if (eventInheritance) { 
  6.             // 查找当前事件类型的Class,连同当前事件类型的Class保存到集合 
  7.             List<Class<?>> eventTypes = lookupAllEventTypes(eventClass); 
  8.             int countTypes = eventTypes.size(); 
  9.             // 遍历Class集合,继续处理事件 
  10.             for (int h = 0; h < countTypes; h++) { 
  11.                 Class<?> clazz = eventTypes.get(h); 
  12.                 subscriptionFound |= postSingleEventForEventType(event, postingState, clazz); 
  13.             } 
  14.         } else { 
  15.             subscriptionFound = postSingleEventForEventType(event, postingState, eventClass); 
  16.         } 
  17.         if (!subscriptionFound) { 
  18.             if (logNoSubscriberMessages) { 
  19.                 logger.log(Level.FINE, "No subscribers registered for event " + eventClass); 
  20.             } 
  21.             if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class && 
  22.                     eventClass != SubscriberExceptionEvent.class) { 
  23.                 post(new NoSubscriberEvent(this, event)); 
  24.             } 
  25.         } 
  26.     } 

postSingleEvent()方法中,根据eventInheritance属性,决定是否向上遍历事件的父类型,然后用postSingleEventForEventType()方法进一步处理事件

  1. private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) { 
  2.         CopyOnWriteArrayList<Subscription> subscriptions; 
  3.         synchronized (this) { 
  4.             // 获取事件类型对应的Subscription集合 
  5.             subscriptions = subscriptionsByEventType.get(eventClass); 
  6.         } 
  7.         // 如果已订阅了对应类型的事件 
  8.         if (subscriptions != null && !subscriptions.isEmpty()) { 
  9.             for (Subscription subscription : subscriptions) { 
  10.                 // 记录事件 
  11.                 postingState.event = event; 
  12.                 // 记录对应的subscription 
  13.                 postingState.subscription = subscription; 
  14.                 boolean aborted = false
  15.                 try { 
  16.                     // 最终的事件处理 
  17.                     postToSubscription(subscription, event, postingState.isMainThread); 
  18.                     aborted = postingState.canceled; 
  19.                 } finally { 
  20.                     postingState.event = null
  21.                     postingState.subscription = null
  22.                     postingState.canceled = false
  23.                 } 
  24.                 if (aborted) { 
  25.                     break; 
  26.                 } 
  27.             } 
  28.             return true
  29.         } 
  30.         return false
  31.     } 

postSingleEventForEventType()方法核心就是遍历发送的事件类型对应的Subscription集合,然后调用postToSubscription()方法处理事件

5、事件处理

postToSubscription()内部会根据订阅事件方法的线程模式,间接或直接的以发送的事件为参数,通过反射执行订阅事件的方法

  1. private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) { 
  2.         // 判断订阅事件方法的线程模式 
  3.         switch (subscription.subscriberMethod.threadMode) { 
  4.             // 默认的线程模式,在那个线程发送事件就在那个线程处理事件 
  5.             case POSTING: 
  6.                 invokeSubscriber(subscription, event); 
  7.                 break; 
  8.             // 在主线程处理事件 
  9.             case MAIN: 
  10.                 // 如果在主线程发送事件,则直接在主线程通过反射处理事件 
  11.                 if (isMainThread) { 
  12.                     invokeSubscriber(subscription, event); 
  13.                 } else { 
  14.                      // 如果是在子线程发送事件,则将事件入队列,通过Handler切换到主线程执行处理事件 
  15.                     // mainThreadPoster 不为空 
  16.                     mainThreadPoster.enqueue(subscription, event); 
  17.                 } 
  18.                 break; 
  19.             // 无论在那个线程发送事件,都先将事件入队列,然后通过 Handler 切换到主线程,依次处理事件。 
  20.             // mainThreadPoster 不为空 
  21.             case MAIN_ORDERED: 
  22.                 if (mainThreadPoster != null) { 
  23.                     mainThreadPoster.enqueue(subscription, event); 
  24.                 } else { 
  25.                     invokeSubscriber(subscription, event); 
  26.                 } 
  27.                 break; 
  28.             case BACKGROUND: 
  29.                 // 如果在主线程发送事件,则先将事件入队列,然后通过线程池依次处理事件 
  30.                 if (isMainThread) { 
  31.                     backgroundPoster.enqueue(subscription, event); 
  32.                 } else { 
  33.                     // 如果在子线程发送事件,则直接在发送事件的线程通过反射处理事件 
  34.                     invokeSubscriber(subscription, event); 
  35.                 } 
  36.                 break; 
  37.             // 无论在那个线程发送事件,都将事件入队列,然后通过线程池处理。 
  38.             case ASYNC: 
  39.                 asyncPoster.enqueue(subscription, event); 
  40.                 break; 
  41.             default
  42.                 throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode); 
  43.         } 
  44.     } 

可以看到,postToSubscription()方法就是根据订阅事件方法的线程模式、以及发送事件的线程来判断如何处理事件,至于处理方式主要有两种:

一种是在相应线程直接通过invokeSubscriber()方法,用反射来执行订阅事件的方法,这样发送出去的事件就被订阅者接收并做相应处理了,

  1. void invokeSubscriber(Subscription subscription, Object event) { 
  2.         try { 
  3.             subscription.subscriberMethod.method.invoke(subscription.subscriber, event); 
  4.         } catch (InvocationTargetException e) { 
  5.             handleSubscriberException(subscription, event, e.getCause()); 
  6.         } catch (IllegalAccessException e) { 
  7.             throw new IllegalStateException("Unexpected exception", e); 
  8.         } 
  9.     } 

另外一种是先将事件入队列(其实底层是一个List),然后做进一步处理,我们以mainThreadPoster.enqueue(subscription, event)为例简单的分析下,其中mainThreadPoster是HandlerPoster类的一个实例,来看该类的主要实现,

  1. public class HandlerPoster extends Handler implements Poster { 
  2.     private final PendingPostQueue queue; 
  3.     private boolean handlerActive; 
  4.     ...... 
  5.     public void enqueue(Subscription subscription, Object event) { 
  6.         // 用subscription和event封装一个PendingPost对象 
  7.         PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event); 
  8.         synchronized (this) { 
  9.             // 入队列 
  10.             queue.enqueue(pendingPost); 
  11.             if (!handlerActive) { 
  12.                 handlerActive = true
  13.                 // 发送开始处理事件的消息,handleMessage()方法将被执行,完成从子线程到主线程的切换 
  14.                 if (!sendMessage(obtainMessage())) { 
  15.                     throw new EventBusException("Could not send handler message"); 
  16.                 } 
  17.             } 
  18.         } 
  19.     } 
  20.     @Override 
  21.     public void handleMessage(Message msg) { 
  22.         boolean rescheduled = false
  23.         try { 
  24.             long started = SystemClock.uptimeMillis(); 
  25.             // 死循环遍历队列 
  26.             while (true) { 
  27.                 // 出队列 
  28.                 PendingPost pendingPost = queue.poll(); 
  29.                 ...... 
  30.                 // 进一步处理pendingPost 
  31.                 eventBus.invokeSubscriber(pendingPost); 
  32.                 ...... 
  33.             } 
  34.         } finally { 
  35.             handlerActive = rescheduled; 
  36.         } 
  37.     } 

所以HandlerPoster的enqueue()方法主要就是将subscription、event对象封装成一个PendingPost对象,然后保存到队列里,之后通过Handler切换到主线程,在handleMessage()方法将中将PendingPost对象循环出队列,交给invokeSubscriber()方法进一步处理:

  1. void invokeSubscriber(PendingPost pendingPost) { 
  2.         Object event = pendingPost.event; 
  3.         Subscription subscription = pendingPost.subscription; 
  4.         // 释放pendingPost引用的资源 
  5.         PendingPost.releasePendingPost(pendingPost); 
  6.         if (subscription.active) { 
  7.             // 用反射来执行订阅事件的方法 
  8.             invokeSubscriber(subscription, event); 
  9.         } 
  10.     } 

这个方法很简单,主要就是从pendingPost中取出之前保存的event、subscription,然后用反射来执行订阅事件的方法,又回到了第一种处理方式。所以mainThreadPoster.enqueue(subscription, event)的核心就是先将将事件入队列,然后通过Handler从子线程切换到主线程中去处理事件;

backgroundPoster.enqueue()和asyncPoster.enqueue也类似,内部都是先将事件入队列,然后再出队列,但是会通过线程池去进一步处理事件。

总结:

  • EventBus底层采用的是注解和反射的方式来获取订阅方法信息;
  • 整个EventBus可以看出,事件是被观察者,订阅者类是观察者,当事件出现或者发送变更的时候,会通过EventBus通知观察者,使得观察者的订阅方法能够被自动调用;

本文转载自微信公众号「 Android开发编程」,可以通过以下二维码关注。转载本文请联系 Android开发编程公众号。

 

责任编辑:姜华 来源: Android开发编程
相关推荐

2021-07-08 10:08:03

DvaJS前端Dva

2021-06-30 08:45:02

内存管理面试

2022-06-07 10:13:22

前端沙箱对象

2020-03-18 14:00:47

MySQL分区数据库

2023-09-08 08:20:46

ThreadLoca多线程工具

2020-12-07 06:19:50

监控前端用户

2021-01-13 05:21:59

参数

2019-11-06 17:30:57

cookiesessionWeb

2023-09-22 10:45:47

云原生云计算

2023-04-12 08:38:44

函数参数Context

2021-08-05 06:54:05

观察者订阅设计

2022-04-11 10:56:43

线程安全

2022-02-14 21:17:21

RPC框架协议

2021-01-06 13:52:19

zookeeper开源分布式

2023-12-15 15:55:24

Linux线程同步

2023-11-23 06:50:08

括号

2020-12-18 09:36:01

JSONP跨域面试官

2019-12-04 13:50:07

CookieSessionToken

2023-01-27 18:55:37

Python内置函数

2021-04-27 19:21:48

HBase原理开源
点赞
收藏

51CTO技术栈公众号