Android 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的一個查找功能。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章