EventBus 3.0进阶:源码及其设计模式 完全解析

thau6663 7年前
   <h2><strong>本文导读</strong></h2>    <p>由于EventBus较为复杂,因此本文也相当长,所以本文分为以下几个部分:创建、注册、发送事件、关于粘性事件的解析、以及最后的思考。读者可以有选择性地选取某部分来进行阅读。</p>    <h2><strong>实现原理</strong></h2>    <h2><strong>创建</strong></h2>    <p>上一篇文章提到,要想注册成为订阅者,必须在一个类中调用如下:</p>    <pre>  <code class="language-java">EventBus.getDefault().register(this);</code></pre>    <p>那么,我们看一下getDefault()的源码是怎样的, <strong>EventBus#getDefault()</strong> :</p>    <pre>  <code class="language-java">public static EventBus getDefault() {      if (defaultInstance == null) {          synchronized (EventBus.class) {              if (defaultInstance == null) {                  defaultInstance = new EventBus();              }          }      }      return defaultInstance;  }</code></pre>    <p>可以看出,这里使用了 <strong>单例模式</strong> ,而且是双重校验的单例,确保在不同线程中也只存在一个EvenBus的实例。</p>    <p>单例模式:一个类有且仅有一个实例,并且自行实例化向整个系统提供。</p>    <p>然而,我们看看EventBus的构造方法:</p>    <pre>  <code class="language-java">/**     * 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);  }</code></pre>    <p>它的构造方法并没有设置成私有的!这是为什么?从注解我们看到,每一个EventBus都是独立地、处理它们自己的事件,因此可以存在多个EventBus,而 通过getDefault()方法获取的实例,则是它已经帮我们构建好的EventBus,是单例,无论在什么时候通过这个方法获取的实例都是同一个实例 。除此之外,我们可以通过建造者帮我们建造具有不同功能的EventBus。</p>    <p>我们继续看上面的this(DEFAULT_BUILDER)调用了另一个构造方法:</p>    <pre>  <code class="language-java">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);      //一系列的builder赋值  }</code></pre>    <p>可以看出,对成员变量进行了一系列的初始化,那么我们来看看几个关键的成员变量:</p>    <pre>  <code class="language-java">private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;  private final Map<Object, List<Class<?>>> typesBySubscriber;  private final Map<Class<?>, Object> stickyEvents;</code></pre>    <p>subscriptionsByEventType:以event(即事件类)为key,以订阅列表(Subscription)为value,事件发送之后,在这里寻找订阅者,而Subscription又是一个CopyOnWriteArrayList,这是一个线程安全的容器。你们看会好奇,Subscription到底是什么,其实看下去就会了解的,现在先提前说下:Subscription是一个封装类,封装了订阅者、订阅方法这两个类。</p>    <p>typesBySubscriber:以订阅者类为key,以event事件类为value,在进行register或unregister操作的时候,会操作这个map。</p>    <p>stickyEvents:保存的是粘性事件,粘性事件上一篇文章有详细描述。</p>    <p>回到EventBus的构造方法,接下来实例化了三个Poster,分别是mainThreadPoster、backgroundPoster、asyncPoster等,这三个Poster是用来处理粘性事件的,我们下面会展开讲述。接着,就是对builder的一系列赋值了,这里使用了 <strong>建造者模式</strong> 。</p>    <p>建造者模式:将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示。</p>    <p>这里的建造者是 <strong>EventBusBuilder</strong> ,它的一系列方法用于配置EventBus的属性,使用getDefault()方法获取的实例,会有着默认的配置,上面说过,EventBus的构造方法是公有的,所以我们可以通过给EventBusBuilder设置不同的属性,进而获取有着不同功能的EventBus。那么我们来列举几个常用的属性加以讲解:</p>    <pre>  <code class="language-java">//默认地,EventBus会考虑事件的超类,即事件如果继承自超类,那么该超类也会作为事件发送给订阅者。  //如果设置为false,则EventBus只会考虑事件类本身。  boolean eventInheritance = true;  public EventBusBuilder eventInheritance(boolean eventInheritance) {      this.eventInheritance = eventInheritance;      return this;  }    //当订阅方法是以onEvent开头的时候,可以调用该方法来跳过方法名字的验证,订阅这类会保存在List中  List<Class<?>> skipMethodVerificationForClasses;  public EventBusBuilder skipMethodVerificationFor(Class<?> clazz) {      if (skipMethodVerificationForClasses == null) {          skipMethodVerificationForClasses = new ArrayList<>();      }      skipMethodVerificationForClasses.add(clazz);      return this;  }    //更多的属性配置请参考源码,均有注释  //...</code></pre>    <p>那么,我们通过建造者模式来手动创建一个EventBus,而不是使用getDefault()方法:</p>    <pre>  <code class="language-java">EventBus eventBus = EventBus.builder()          .eventInheritance(false)          .sendNoSubscriberEvent(true)          .skipMethodVerificationFor(MainActivity.class)          .build();</code></pre>    <h2><strong>注册</strong></h2>    <p>好了,以上说了一大推关于EventBus的创建,接下来,我们继续讲它的注册过程。要想使一个类成为订阅者,那么这个类必须有一个订阅方法,以@Subscribe注解标记的方法,接着调用register()方法来进行注册。那么我们直接来看 <strong>EventBus#register()</strong> 。</p>    <h3>register</h3>    <pre>  <code class="language-java">public void register(Object subscriber) {      Class<?> subscriberClass = subscriber.getClass();      List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);      synchronized (this) {          for (SubscriberMethod subscriberMethod : subscriberMethods) {              subscribe(subscriber, subscriberMethod);          }      }  }</code></pre>    <p>先获取了订阅者类的class,接着交给SubscriberMethodFinder.findSubscriberMethods()处理,返回结果保存在List<SubscriberMethod>中,由此可推测通过上面的方法把订阅方法找出来了,并保存在集合中,那么我们直接看这个方法, <strong>SubscriberMethodFinder#findSubscriberMethods()</strong> 。</p>    <h3>findSubscriberMethods</h3>    <pre>  <code class="language-java">List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {      //首先从缓存中取出subscriberMethodss,如果有则直接返回该已取得的方法      List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);      if (subscriberMethods != null) {          return subscriberMethods;      }      //从EventBusBuilder可知,ignoreGenerateIndex一般为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 {          //将获取的subscriberMeyhods放入缓存中          METHOD_CACHE.put(subscriberClass, subscriberMethods);          return subscriberMethods;      }  }</code></pre>    <p>从上面的逻辑可以知道,一般会调用findUsingInfo方法,我们接着看 <strong>SubscriberMethodFinder#findUsingInfo</strong> 方法:</p>    <h3><strong>findUsingInfo</strong></h3>    <pre>  <code class="language-java">private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {      //准备一个FindState,该FindState保存了订阅者类的信息      FindState findState = prepareFindState();      //对FindState初始化      findState.initForSubscriber(subscriberClass);      while (findState.clazz != null) {          //获得订阅者的信息,一开始会返回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 {              //1 、到了这里              findUsingReflectionInSingleClass(findState);          }          //移动到父类继续查找          findState.moveToSuperclass();      }      return getMethodsAndRelease(findState);  }</code></pre>    <p>上面用到了FindState这个内部类来保存订阅者类的信息,我们看看它的内部结构:</p>    <h3><strong>FindState</strong></h3>    <pre>  <code class="language-java">static class FindState {      //订阅方法的列表      final List<SubscriberMethod> subscriberMethods = new ArrayList<>();      //以event为key,以method为value      final Map<Class, Object> anyMethodByEventType = new HashMap<>();      //以method的名字生成一个method为key,以订阅者类为value      final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();      final StringBuilder methodKeyBuilder = new StringBuilder(128);        Class<?> subscriberClass;      Class<?> clazz;      boolean skipSuperClasses;      SubscriberInfo subscriberInfo;        //对FindState初始化      void initForSubscriber(Class<?> subscriberClass) {          this.subscriberClass = clazz = subscriberClass;          skipSuperClasses = false;          subscriberInfo = null;      }        //省略...  }</code></pre>    <p>可以看出,该内部类保存了订阅者及其订阅方法的信息,用Map一一对应进行保存,接着利用initForSubscriber进行初始化,这里subscriberInfo初始化为null,因此在 <strong>SubscriberMethodFinder#findUsingInfo</strong> 里面,会直接调用到①号代码,即调用 SubscriberMethodFinder#findUsingReflectionInSingleClass ,这个方法非常重要!!!在这个方法内部,利用反射的方式,对订阅者类进行扫描,找出订阅方法,并用上面的Map进行保存,我们来看这个方法。</p>    <h3><strong>findUsingReflectionInSingleClass</strong></h3>    <pre>  <code class="language-java">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注解                  Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);                  if (subscribeAnnotation != null) {                      //参数类型 即为 事件类型                      Class<?> eventType = parameterTypes[0];                      // 2 、调用checkAdd方法                      if (findState.checkAdd(method, eventType)) {                          //从注解中提取threadMode                          ThreadMode threadMode = subscribeAnnotation.threadMode();                          //新建一个SubscriberMethod对象,并添加到findState的subscriberMethods这个集合内                          findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,                                  subscribeAnnotation.priority(), subscribeAnnotation.sticky()));                      }                  }              //如果开启了严格验证,同时当前方法又有@Subscribe注解,对不符合要求的方法会抛出异常              } 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");          }      }  }</code></pre>    <p>虽然该方法比较长,但是逻辑非常清晰,逐一判断订阅者类是否存在订阅方法,如果符合要求,并且②号代码调用 <strong>FindState#checkAdd</strong> 方法返回true的时候,才会把方法保存在findState的subscriberMethods内。而SubscriberMethod则是用于保存订阅方法的一个类。那么我们来看看 <strong>FindState#checkAdd</strong> 做了什么工作。</p>    <h3><strong>checkAdd</strong></h3>    <pre>  <code class="language-java">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);      }  }</code></pre>    <p>从注释可知,这里包含两重检验,第一层检验是判断eventType的类型,而第二次检验是判断方法的完整签名。首先通过anyMethodByEventType.put(eventType, method) 将eventType以及method放进anyMethodByEventType这个Map中(上面提到),同时该put方法会返回同一个key的上一个value值,所以如果之前没有别的方法订阅了该事件,那么existing应该为null,可以直接返回true;否则为某一个订阅方法的实例,要进行下一步的判断。接着往下走,会调用 <strong>checkAddWithMethodSignature()</strong> 方法。</p>    <h3><strong>checkAddWithMethodSignature</strong></h3>    <pre>  <code class="language-java">private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {      methodKeyBuilder.setLength(0);      methodKeyBuilder.append(method.getName());      methodKeyBuilder.append('>').append(eventType.getName());        //methodKey由方法名与事件名组成      String methodKey = methodKeyBuilder.toString();      //获取当前方法所在的类的类名      Class<?> methodClass = method.getDeclaringClass();      //给subscriberClassByMethodKey赋值,并返回上一个相同key的 类名      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;      }  }</code></pre>    <p>从上面的代码看出,该方法首先获取了当前方法的methodKey、methodClass等,并赋值给subscriberClassByMethodKey,如果方法签名相同,那么返回旧值给methodClassOld,接着是一个if判断,判断methodClassOld是否为空,由于第一次调用该方法的时候methodClassOld肯定是null,此时就可以直接返回true了。但是,后面还有一个判断即 <strong>methodClassOld.isAssignableFrom(methodClass)</strong> ,这个的意思是:methodClassOld是否是methodClass的父类或者同一个类。如果这两个条件都不满足,则会返回false,那么当前方法就不会添加为订阅方法了。</p>    <p>那么,说了一大堆关于 <strong>checkAdd</strong> 和 <strong>checkAddWithMethodSignature</strong> 方法的源码,那么这两个方法到底有什么作用呢?从这两个方法的逻辑来看,第一层判断根据eventType来判断是否有多个方法订阅该事件,而第二层判断根据完整的方法签名(包括方法名字以及参数名字)来判断。下面是笔者的理解:</p>    <p>第一种情况:比如一个类有多个订阅方法,方法名不同,但它们的参数类型都是相同的(虽然一般不这样写,但不排除这样的可能),那么遍历这些方法的时候,会多次调用到checkAdd方法,由于existing不为null,那么会进而调用checkAddWithMethodSignature方法,但是由于每个方法的名字都不同,因此methodClassOld会一直为null,因此都会返回true。也就是说, <strong>允许一个类有多个参数相同的订阅方法</strong> 。</p>    <p>第二种情况:类B继承自类A,而每个类都是有相同订阅方法,换句话说,类B的订阅方法继承并重写自类A,它们都有着一样的方法签名。方法的遍历会从子类开始,即B类,在checkAddWithMethodSignature方法中,methodClassOld为null,那么B类的订阅方法会被添加到列表中。接着,向上找到类A的订阅方法,由于methodClassOld不为null而且显然类B不是类A的父类,methodClassOld.isAssignableFrom(methodClass)也会返回false,那么会返回false。也就是说, 子类继承并重写了父类的订阅方法,那么只会把子类的订阅方法添加到订阅者列表,父类的方法会忽略 。</p>    <p>让我们回到findUsingReflectionInSingleClass方法,当遍历完当前类的所有方法后,会回到 <strong>findUsingInfo</strong> 方法,接着会执行最后一行代码,即return getMethodsAndRelease(findState);那么我们继续看 <strong>SubscriberMethodFinder#getMethodsAndRelease</strong> 方法。</p>    <h3><strong>getMethodsAndRelease</strong></h3>    <pre>  <code class="language-java">private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {      //从findState获取subscriberMethods,放进新的ArrayList      List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);      //把findState回收      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;  }</code></pre>    <p>通过该方法,把subscriberMethods不断逐层返回,直到返回 <strong>EventBus#register()</strong> 方法,最后开始遍历每一个订阅方法,并调用subscribe(subscriber, subscriberMethod)方法,那么,我们继续来看 <strong>EventBus#subscribe</strong> 方法。</p>    <h3><strong>subscribe</strong></h3>    <p>在该方法内,主要是实现订阅方法与事件直接的关联,即注册,即放进我们上面提到关键的几个Map中:subscriptionsByEventType、typesBySubscriber、stickyEvents。</p>    <pre>  <code class="language-java">private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {      Class<?> eventType = subscriberMethod.eventType;      //将subscriber和subscriberMethod封装成 Subscription      Subscription newSubscription = new Subscription(subscriber, subscriberMethod);      //根据事件类型获取特定的 Subscription      CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);      //如果为null,说明该subscriber尚未注册该事件      if (subscriptions == null) {          subscriptions = new CopyOnWriteArrayList<>();          subscriptionsByEventType.put(eventType, subscriptions);      } else {          //如果不为null,并且包含了这个subscription 那么说明该subscriber已经注册了该事件,抛出异常          if (subscriptions.contains(newSubscription)) {              throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "                      + eventType);          }      }        //根据优先级来设置放进subscriptions的位置,优先级高的会先被通知      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;          }      }        //根据subscriber(订阅者)来获取它的所有订阅事件      List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);      if (subscribedEvents == null) {          subscribedEvents = new ArrayList<>();          //把订阅者、事件放进typesBySubscriber这个Map中          typesBySubscriber.put(subscriber, subscribedEvents);      }      subscribedEvents.add(eventType);        //下面是对粘性事件的处理      if (subscriberMethod.sticky) {          //从EventBusBuilder可知,eventInheritance默认为true.          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 {              //根据eventType,从stickyEvents列表中获取特定的事件              Object stickyEvent = stickyEvents.get(eventType);              //分发事件              checkPostStickyEventToSubscription(newSubscription, stickyEvent);          }      }  }</code></pre>    <p>到目前为止,注册流程基本分析完毕,而关于最后的粘性事件的处理,这里暂时不说,下面会详细进行讲述。可以看出,整个注册流程非常地长,方法的调用栈很深,在各个方法中不断跳转,那么为了方便读者理解,下面给出一个流程图,读者可结合该流程图以及上面的详解来进行理解。</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/bb523c79da29ead5dbdbd816014e89c7.jpg"></p>    <p style="text-align:center">注册流程</p>    <h2><strong>注销</strong></h2>    <p>与注册相对应的是注销,当订阅者不再需要事件的时候,我们要注销这个订阅者,即调用以下代码:</p>    <pre>  <code class="language-java">EventBus.getDefault().unregister(this);</code></pre>    <p>那么我们来分析注销流程是怎样实现的,首先查看 <strong>EventBus#unregister</strong> :</p>    <h3><strong>unregister</strong></h3>    <pre>  <code class="language-java">public synchronized void unregister(Object subscriber) {      //根据当前的订阅者来获取它所订阅的所有事件      List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);      if (subscribedTypes != null) {          //遍历所有订阅的事件          for (Class<?> eventType : subscribedTypes) {              unsubscribeByEventType(subscriber, eventType);          }          //从typesBySubscriber中移除该订阅者          typesBySubscriber.remove(subscriber);      } else {          Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());      }  }</code></pre>    <p>上面调用了 <strong>EventBus#unsubscribeByEventType</strong> ,把订阅者以及事件作为参数传递了进去,那么应该是解除两者的联系。</p>    <h3><strong>unsubscribeByEventType</strong></h3>    <pre>  <code class="language-java">private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {      //根据事件类型从subscriptionsByEventType中获取相应的 subscriptions 集合      List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);      if (subscriptions != null) {          int size = subscriptions.size();          //遍历所有的subscriptions,逐一移除          for (int i = 0; i < size; i++) {              Subscription subscription = subscriptions.get(i);              if (subscription.subscriber == subscriber) {                  subscription.active = false;                  subscriptions.remove(i);                  i--;                  size--;              }          }      }  }</code></pre>    <p>可以看到,上面两个方法的逻辑是非常清楚的,都是从typesBySubscriber或subscriptionsByEventType移除相应与订阅者有关的信息,注销流程相对于注册流程简单了很多,其实注册流程主要逻辑集中于怎样找到订阅方法上。</p>    <h2><strong>发送事件</strong></h2>    <p>接下来,我们分析发送事件的流程,一般地,发送一个事件调用以下代码:</p>    <pre>  <code class="language-java">EventBus.getDefault().post(new MessageEvent("Hello !....."));`</code></pre>    <p>我们来看看 <strong>EventBus#post</strong> 方法。</p>    <h3><strong>post</strong></h3>    <pre>  <code class="language-java">public void post(Object event) {      //1、 获取一个postingState      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;          }      }  }</code></pre>    <p>逻辑非常清晰,首先是获取一个PostingThreadState,那么PostingThreadState是什么呢?我们来看看它的类结构:</p>    <h3><strong>PostingThreadState</strong></h3>    <pre>  <code class="language-java">final static class PostingThreadState {      final List<Object> eventQueue = new ArrayList<Object>();      boolean isPosting;      boolean isMainThread;      Subscription subscription;      Object event;      boolean canceled;  }</code></pre>    <p>可以看出,该PostingThreadState主要是封装了当前线程的信息,以及订阅者、订阅事件等。那么怎么得到这个PostingThreadState呢?让我们回到post()方法,看①号代码,这里通过currentPostingThreadState.get()来获取PostingThreadState。那么currentPostingThreadState又是什么呢?</p>    <pre>  <code class="language-java">private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {      @Override      protected PostingThreadState initialValue() {          return new PostingThreadState();      }  };</code></pre>    <p>原来 currentPostingThreadState是一个ThreadLocal,而ThreadLocal是每个线程独享的,其数据别的线程是不能访问的,因此是线程安全的。我们再次回到Post()方法,继续往下走,是一个while循环,这里不断地从队列中取出事件,并且分发出去,调用的是 <strong>EventBus#postSingleEvent</strong> 方法。</p>    <h3><strong>postSingleEvent</strong></h3>    <pre>  <code class="language-java">private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {      Class<?> eventClass = event.getClass();      boolean subscriptionFound = false;      //该eventInheritance上面有提到,默认为true,即EventBus会考虑事件的继承树      //如果事件继承自父类,那么父类也会作为事件被发送      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));          }      }  }</code></pre>    <p>从上面的逻辑来看,对于一个事件,默认地会搜索出它的父类,并且把父类也作为事件之一发送给订阅者,接着调用了 <strong>EventBus#postSingleEventForEventType</strong> ,把事件、postingState、事件的类传递进去,那么我们来看看这个方法。</p>    <h3><strong>postSingleEventForEventType</strong></h3>    <pre>  <code class="language-java">private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {      CopyOnWriteArrayList<Subscription> subscriptions;      synchronized (this) {          //从subscriptionsByEventType获取响应的subscriptions          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;              }               //...          }          return true;      }      return false;  }</code></pre>    <p>接着,进一步调用了 <strong>EventBus#postToSubscription</strong> ,可以发现,这里把订阅列表作为参数传递了进去,显然,订阅列表内部保存了订阅者以及订阅方法,那么可以猜测,这里应该是通过反射的方式来调用订阅方法。具体怎样的话,我们看源码。</p>    <h3><strong>postToSubscription</strong></h3>    <pre>  <code class="language-java">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);      }  }</code></pre>    <p>首先获取threadMode,即订阅方法运行的线程,如果是POSTING,那么直接调用invokeSubscriber()方法即可,如果是MAIN,则要判断当前线程是否是MAIN线程,如果是也是直接调用invokeSubscriber()方法,否则会交给mainThreadPoster来处理,其他情况相类似。这里会用到三个Poster,由于粘性事件也会用到这三个Poster,因此我把它放到下面来专门讲述。而 <strong>EventBus#invokeSubscriber</strong> 的实现也很简单,主要实现了 <strong>利用反射的方式</strong> 来调用订阅方法,这样就实现了事件发送给订阅者,订阅者调用订阅方法这一过程。如下所示:</p>    <h3><strong>invokeSubscriber</strong></h3>    <pre>  <code class="language-java">void invokeSubscriber(Subscription subscription, Object event) {      try {          subscription.subscriberMethod.method.invoke(subscription.subscriber, event);      }       //...  }</code></pre>    <p>到目前为止,事件的发送流程也讲解完毕,为了方便理解,整个发送流程也给出相应的流程图:</p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/47c4817057e28a39f2795e60751faad3.jpg"></p>    <p>发送流程.jpg</p>    <h2><strong>粘性事件的发送及接收分析</strong></h2>    <p>粘性事件与一般的事件不同,粘性事件是先发送出去,然后让后面注册的订阅者能够收到该事件。粘性事件的发送是通过 <strong>EventBus#postSticky()</strong> 方法进行发送的,我们来看它的源码:</p>    <pre>  <code class="language-java">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(event);  }</code></pre>    <p>把该事件放进了 stickyEvents这个map中,接着调用了post()方法,那么流程和上面分析的一样了,只不过是找不到相应的subscriber来处理这个事件罢了。那么为什么当注册订阅者的时候可以马上接收到匹配的事件呢?还记得上面的EventBus#subscribe方法里面有一段是专门处理粘性事件的代码吗?即:</p>    <pre>  <code class="language-java">private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {      //以上省略...      //下面是对粘性事件的处理      if (subscriberMethod.sticky) {          //从EventBusBuilder可知,eventInheritance默认为true.          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 {              //根据eventType,从stickyEvents列表中获取特定的事件              Object stickyEvent = stickyEvents.get(eventType);              //分发事件              checkPostStickyEventToSubscription(newSubscription, stickyEvent);          }      }  }</code></pre>    <p>上面的逻辑很清晰,EventBus并不知道当前的订阅者对应了哪个粘性事件,因此需要全部遍历一次,找到匹配的粘性事件后,会调用 <strong>EventBus#checkPostStickyEventToSubscription</strong> 方法:</p>    <pre>  <code class="language-java">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());      }  }</code></pre>    <p>接着,又回到了postToSubscription方法了,无论对于普通事件或者粘性事件,都会根据threadMode来选择对应的线程来执行订阅方法,而切换线程的关键所在就是mainThreadPoster、backgroundPoster和asyncPoster这三个Poster。</p>    <h3><strong>HandlerPoster</strong></h3>    <p>我们首先看mainThreadPoster,它的类型是HandlerPoster继承自Handler:</p>    <pre>  <code class="language-java">final class HandlerPoster extends Handler {        //PendingPostQueue队列,待发送的post队列      private final PendingPostQueue queue;      //规定最大的运行时间,因为运行在主线程,不能阻塞主线程      private final int maxMillisInsideHandleMessage;      private final EventBus eventBus;      private boolean handlerActive;      //省略...  }</code></pre>    <p>可以看到,该handler内部有一个PendingPostQueue,这是一个队列,保存了PendingPost,即待发送的post,该PendingPost封装了event和subscription,方便在线程中进行信息的交互。在postToSubscription方法中,当前线程如果不是主线程的时候,会调用 <strong>HandlerPoster#enqueue</strong> 方法:</p>    <pre>  <code class="language-java">void enqueue(Subscription subscription, Object event) {      //将subscription和event打包成一个PendingPost      PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);      synchronized (this) {          //入队列          queue.enqueue(pendingPost);          if (!handlerActive) {              handlerActive = true;              //发送消息,在主线程运行              if (!sendMessage(obtainMessage())) {                  throw new EventBusException("Could not send handler message");              }          }      }  }</code></pre>    <p>首先会从PendingPostPool中获取一个可用的PendingPost,接着把该PendingPost放进PendingPostQueue,发送消息,那么由于该HandlerPoster在初始化的时候获取了UI线程的Looper,所以它的handleMessage()方法运行在UI线程:</p>    <pre>  <code class="language-java">@Override  public void handleMessage(Message msg) {      boolean rescheduled = false;      try {          long started = SystemClock.uptimeMillis();          //不断从队列中取出pendingPost          while (true) {              //省略...              eventBus.invokeSubscriber(pendingPost);                      //..          }      } finally {          handlerActive = rescheduled;      }  }</code></pre>    <p>里面调用到了 <strong>EventBus#invokeSubscriber</strong> 方法,在这个方法里面,将PendingPost解包,进行正常的事件分发,这上面都说过了,就不展开说了。</p>    <h3><strong>BackgroundPoster</strong></h3>    <p>BackgroundPoster继承自Runnable,与HandlerPoster相似的,它内部都有PendingPostQueue这个队列,当调用到它的enqueue的时候,会将subscription和event打包成PendingPost:</p>    <pre>  <code class="language-java">public void enqueue(Subscription subscription, Object event) {      PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);      synchronized (this) {          queue.enqueue(pendingPost);          //如果后台线程还未运行,则先运行          if (!executorRunning) {              executorRunning = true;              //会调用run()方法              eventBus.getExecutorService().execute(this);          }      }  }</code></pre>    <p>该方法通过Executor来运行run()方法,run()方法内部也是调用到了 <strong>EventBus#invokeSubscriber</strong> 方法。</p>    <h3><strong>AsyncPoster</strong></h3>    <p>与BackgroundPoster类似,它也是一个Runnable,实现原理与BackgroundPoster大致相同,但有一个不同之处,就是它内部不用判断之前是否已经有一条线程已经在运行了,它每次post事件都会使用新的一条线程。</p>    <h2><strong>再谈观察者模式</strong></h2>    <p>整个EventBus是基于观察者模式而构建的,而上面的调用观察者的方法则是观察者模式的核心所在。</p>    <p>观察者模式:定义了对象之间的一对多依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。</p>    <p>从整个EventBus可以看出,事件是被观察者,订阅者类是观察者,当事件出现或者发送变更的时候,会通过EventBus通知观察者,使得观察者的订阅方法能够被自动调用。当然了,这与一般的观察者模式有所不同。回想我们所用过的观察者模式,我们会让事件实现一个接口或者直接继承自Java内置的Observerable类,同时在事件内部还持有一个列表,保存所有已注册的观察者,而事件类还有一个方法用于通知观察者的。那么从 <strong>单一职责原则</strong> 的角度来说,这个事件类所做的事情太多啦!既要记住有哪些观察者,又要等到时机成熟的时候通知观察者,又或者有别的自身的方法。这样的话,一两件事件类还好,但如果对于每一个事件类,每一个新的不同的需求,都要实现相同的操作的话,这是非常繁琐而且低效率的。因此, <strong>EventBus就充当了中介的角色</strong> ,把事件的很多责任抽离出来,使得事件自身不需要实现任何东西,别的都交给EventBus来操作就可以了。</p>    <p>好了,本文到此为止已经对EventBus进行了一次详细的讲解,由于本文很长,建议读者可以选择难懂的部分对照源码反复思考以便能深刻理解。最后,为坚持读完本文的你点赞,谢谢你们的阅读!</p>    <p> </p>    <p> </p>    <p>来自:http://www.jianshu.com/p/bda4ed3017ba</p>    <p> </p>