EventBus3.0源码简析

本文主要通过源码讲解EventBus的内部实现,如果还没有使用过该框架的朋友,可以先参考这篇文章
Android事件总线(一)EventBus3.0用法全解析

基于EventBus版本:3.1.1

1. 前言

    EventBus是一个基于观察者模式的事件发布/订阅框架,它能有效的解决android中组件的通信问题。理解框架的基本原理有助于更好的运用框架和查找问题,本文采用源码+注释+说明的形式带领大家来解读EventBus的原理,在下一篇会介绍如何优化EventBus的查找流程。

2. 源码解读


构造方法

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();	//默认的构造器

public static EventBus getDefault() {
 if (defaultInstance == null) {
       synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
 }
 
public static EventBusBuilder builder() {
      return new EventBusBuilder();
  }
  
public EventBus() {
   this(DEFAULT_BUILDER);
}
 
EventBus(EventBusBuilder builder) {
	...
 	//初始化各种属性
 	...
 }

    EventBus采用建造者模式来构建,通常我们通过getDefault来获得一个单例的EventBus实例。EventBus有几个比较重要的Map结构,我们来看看:

 
 private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
 
 private final Map<Object, List<Class<?>>> typesBySubscriber;
 
 private final Map<Class<?>, Object> stickyEvents;

需要注意的是,在EventBus中,事件类型是以事件类的Class对象来表示的,所以上面三个Map中的Class<?>都表示事件,接下来介绍下这三个属性:

  • subscriptionsByEventType 存放所有的订阅事件。因为EventBus是通过方法去发布事件的,可以理解为最终接收到事件的是每个method。
  • typesBySubscriber 存放每个订阅者的订阅的所有事件类型,用于解绑操作。
  • stickyEvents 存放粘性事件的实例

注册/订阅

注册/订阅调用的是register方法:

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();	
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);//-->1
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);//-->2
        }
    }
}
  1. 在1处:找到这个订阅者(例如:MainActivity)里面所有的订阅方法(用@Subscribe注解的方法)
  2. 在2处:遍历SubscriberMethod数组,调用subscribe()

至于findSubscriberMethods()怎么实现我们放到后面,通常情况下是通过反射来找到使用@Subscribe注解过的方法,我们来看看subscribe() 的实现:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
      Class<?> eventType = subscriberMethod.eventType;
      Subscription newSubscription = new Subscription(subscriber, subscriberMethod);	//-->1
      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++) { //-->2
          if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
              subscriptions.add(i, newSubscription);
              break;
          }
      }

      List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
      if (subscribedEvents == null) { //-->3
          subscribedEvents = new ArrayList<>();
          typesBySubscriber.put(subscriber, subscribedEvents);
      }
      subscribedEvents.add(eventType);

      if (subscriberMethod.sticky) { //-->4
          if (eventInheritance) {
              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 {
              Object stickyEvent = stickyEvents.get(eventType);
              checkPostStickyEventToSubscription(newSubscription, stickyEvent);
          }
      }
  }

  1. 在1处:由subscriber和subscriberMethod组合成一个Subscription对象,也就是订阅事件,找到subscriptionsByEventType对应eventType的Subscription集合,如果已经订阅了该事件,则抛出异常。
  2. 在2处:根据优先级,将Subscription添加到Subscription集合中。
  3. 在3处:将event的类型添加到typesBySubscriber中,对应的key就是订阅者。
  4. 在4处:如果订阅方法是粘性的,查看有没有这个类型的粘性事件,有的话就回调这个method。

总结一下EventBus的注册过程:首先通过findSubscriberMethods找到订阅者的所有订阅方法,然后将订阅每个方法(SubscriberMethod )和订阅者组成一个订阅事件根据优先级添加到subscriptionsByEventType中,接着添加事件类型eventType到typesBySubscriber中,最后处理粘性事件。

发布事件

发布事件有postStickypost方法:

public void postSticky(Object event) {
    synchronized (stickyEvents) {
         stickyEvents.put(event.getClass(), event);	
     }
     post(event);
}
    
public void post(Object event) {
   PostingThreadState postingState = currentPostingThreadState.get();	//-->1
   List<Object> eventQueue = postingState.eventQueue;
   eventQueue.add(event);	//--2

   if (!postingState.isPosting) {
       postingState.isMainThread = isMainThread();
       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);	//-->3
           }
       } finally {
           postingState.isPosting = false;
           postingState.isMainThread = false;
       }
   }
}

可以看到,postSticky只是将事件添加到stickyEvents中,最终调用的还是post方法,post方法分为以下几步:

  1. 在1处:获取当前线程的PostingThreadState对象,currentPostingThreadState是一个ThreadLocal示例,PostingThreadState主要包含事件集合和一些状态
  2. 在2处:添加事件到事件集合中
  3. 在3处:循环调用postSingleEvent处理每个事件,直到eventQueue为空

继续看postSingleEvent

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {	//-->1
        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 {	//-->2
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
    if (!subscriptionFound) {
      ...
      //没有找到订阅事件 的处理过程
      ...
    }
}

在1处:判断eventInheritance这个字段,这个字段表示是否支持事件的继承,举个例子,如果EventA继承EventB,也实现EventC接口,那么发送EventA的时候,订阅了EventB和EventC的方法会被通知。这个值默认是true,在lookupAllEventTypes中找到这个事件的所有父类和接口,并循环调用postSingleEventForEventType方法。
在2处:如果eventInheritance为false,直接调用postSingleEventForEventType方法。
可见在1和2处都是调用postSingleEventForEventType进行发布,我们来看postSingleEventForEventType方法:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
     CopyOnWriteArrayList<Subscription> subscriptions;
     synchronized (this) {
         subscriptions = subscriptionsByEventType.get(eventClass);	//-->1
     }
     if (subscriptions != null && !subscriptions.isEmpty()) {
         for (Subscription subscription : subscriptions) {	//-->2
             postingState.event = event;	
             postingState.subscription = subscription;
             boolean aborted = false;
             try {
                 postToSubscription(subscription, event, postingState.isMainThread);//-->3
                 aborted = postingState.canceled;	//-->4
             } finally {
                 postingState.event = null;
                 postingState.subscription = null;
                 postingState.canceled = false;
             }
             if (aborted) {	
                 break;
             }
         }
         return true;
     }
     return false;
 }
  1. 在1处:同步的方式获取对应事件的Subscription对象
  2. 在2处:遍历subscriptions数组,并设置postingState的event和subscription,设置这两个值的作用会在取消事件下发的时候用到,最后调用postToSubscription发布事件。
  3. 在3处:调用postToSubscription发布事件
  4. 在4处:获取postingState.canceled值,当canceled为true时,表情事件被上游接收者取消掉了,退出循环。
    上面说到,subscriptionsByEventType里面的subscriptions是按照优先级排序的,优先级高的在前面,在发布事件的时候会遍历改事件的所有接收者,所以优先级高的接收者可以取消该事件的传递。我们来看看cancelEventDelivery方法:
public void cancelEventDelivery(Object event) {
   PostingThreadState postingState = currentPostingThreadState.get();
   if (!postingState.isPosting) {
       throw new EventBusException(
               "This method may only be called from inside event handling methods on the posting thread");
   } else if (event == null) {
       throw new EventBusException("Event may not be null");
   } else if (postingState.event != event) {
       throw new EventBusException("Only the currently handled event may be aborted");
   } else if (postingState.subscription.subscriberMethod.threadMode != ThreadMode.POSTING) {
       throw new EventBusException(" event handlers may only abort the incoming event");
   }

   postingState.canceled = true;
}

一目了然,postingState.canceled 被设置为true。
到这一步我们应该知道,真正进行回调的过程是在postToSubscription里面进行的(因为是在回调方法里面进行取消),我们来看一下postToSubscription方法:

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
      switch (subscription.subscriberMethod.threadMode) {
          case POSTING:
              invokeSubscriber(subscription, event);
              break;
          case MAIN:
              if (isMainThread) {
                  invokeSubscriber(subscription, event);
              } else {
                  mainThreadPoster.enqueue(subscription, event);
              }
              break;
          case MAIN_ORDERED:
             	//省略
              break;
          case BACKGROUND:
           	   //省略
              break;
          case ASYNC:
         	  //省略
              break;
          default:
              throw new IllegalStateException("Unknown thread mode: " + subscription.subscriberMethod.threadMode);
      }
  }

这里通过注册时的线程模式来区分处理,我们主要看默认的POSTING模式和常用的MAIN模式,其他的线程模式类似。点进去看invokeSubscriber方法:

 void invokeSubscriber(Subscription subscription, Object event) {
     try {
         subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
     } catch (InvocationTargetException e) {
         handleSubscriberException(subscription, event, e.getCause());
     } catch (IllegalAccessException e) {
         throw new IllegalStateException("Unexpected exception", e);
     }
 }

这里就直接调用Method的invoke方法就ok了,不懂的可以看看反射的部分,发布线程是主线程的话,同样调用的是invokeSubscriber,如果发布线程不是主线程的话调用的是 mainThreadPoster.enqueue(subscription, event)。直接看mainThreadPoster的初始化:

//EventBus类
EventBus(EventBusBuilder builder) {
    //....省略无关代码
    mainThreadSupport = builder.getMainThreadSupport();
    mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
  	//....省略无关代码
}

//EventBusBuilder类
MainThreadSupport getMainThreadSupport() {
    if (mainThreadSupport != null) {
        return mainThreadSupport;
    } else if (Logger.AndroidLogger.isAndroidLogAvailable()) {
        Object looperOrNull = getAndroidMainLooperOrNull();
        return looperOrNull == null ? null :
                new MainThreadSupport.AndroidHandlerMainThreadSupport((Looper) looperOrNull);
    } else {
        return null;
    }
}

mainThreadSupport 的类型是MainThreadSupport,它的初始值是由EventBusBuilder的getMainThreadSupport方法获得,getMainThreadSupport主要通过判断当前环境是否是adnroid环境,如果是android环境,获取到主线程的Looper对象,然后调用new MainThreadSupport.AndroidHandlerMainThreadSupport()构造MainThreadSupport,MainThreadSupport是一个接口,如下:

public interface MainThreadSupport {

  boolean isMainThread();

  Poster createPoster(EventBus eventBus);

  class AndroidHandlerMainThreadSupport implements MainThreadSupport {

      private final Looper looper;

      public AndroidHandlerMainThreadSupport(Looper looper) {
          this.looper = looper;
      }

      @Override
      public boolean isMainThread() {
          return looper == Looper.myLooper();
      }

      @Override
      public Poster createPoster(EventBus eventBus) {
          return new HandlerPoster(eventBus, looper, 10);
      }
  }
}

mainThreadPoster 正是调用AndroidHandlerMainThreadSupport的createPoster创建的,createPoster创建了一个HandlerPoster对象,传入的是主线程的Looper对象和EventBus实例,由名字就可以看出,里面是维护了一套Handler的消息发送过程,里面的过程就不再阐述,最终调用的还是invokeSubscriber方法,只不过是在主线中调用而已。

解绑

解绑事件调用的是unregister方法,解绑之后,该对象将接受不到任何事件。来看一下unregister方法:

public synchronized void unregister(Object subscriber) {
   List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);	//-->1
    if (subscribedTypes != null) {
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);	//-->2
        }
        typesBySubscriber.remove(subscriber);	
    } else {
        logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

上文提到subscribedTypes 存放的是每个订阅者订阅的所有事件类型。
在1处:得到该订阅者的所有事件
在2处:循环调用unsubscribeByEventType移除此订阅者的订阅事件
unsubscribeByEventType方法:

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
      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) {
                  subscription.active = false;
                  subscriptions.remove(i);
                  i--;
                  size--;
              }
          }
      }
  }

unsubscribeByEventType方法将存放在subscriptionsByEventType里面和订阅者相关的订阅事件移除。
到这里,EventBus大致的功能就讲清楚了。

3.总结

可以看到,EventBus的源码并不算复杂,前面说到,EventBus默认是通过反射来添加订阅事件的,在性能上有一定的损耗,在下一篇中会讲到如何优化EventBus的一个查找功能。

更多安卓知识体系,请关注公众号:
三分钟Code

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值