EventBus 3.0源碼解析

1.簡介

想必每個入了門的Android開發者都多少對EventBus有過了解,EventBus是一個Android事件發佈/訂閱框架,通過解耦發佈者和訂閱者簡化 Android 事件傳遞。EventBus使用簡單,並將事件發佈和訂閱充分解耦,從而使代碼更簡潔。一直以來很受開發者的歡迎,截止到目前EventBus的安裝量已經超過一億次。足以看出EventBus有多麼的優秀。

網絡上有很多的大神已經寫了不少關於EventBus 3.0的使用及源碼解析文章,我寫這篇文章的目的在於加深自己對這一框架的理解,以及對觀察者模式的認識。參考了其他大神的一些思路。

2.使用方法

這裏寫圖片描述

  • 2.1 導入組件:

    打開App的build.gradle,在dependencies中添加最新的EventBus依賴:

    compile 'org.greenrobot:eventbus:3.0.0'

    如果不需要索引加速的話,就可以直接跳到第二步了。而要應用最新的EventBusAnnotationProcessor則比較麻煩,因爲註解解析依賴於android-apt-plugin。我們一步一步來,首先在項目gradle的dependencies中引入apt編譯插件:

    classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'

    然後在App的build.gradle中應用apt插件,並設置apt生成的索引的包名和類名:

    apply plugin: 'com.neenbedankt.android-apt'
    apt {
        arguments {
            eventBusIndex "com.study.sangerzhong.studyapp.MyEventBusIndex"
        }
    }

    接着在App的dependencies中引入EventBusAnnotationProcessor:

    apt 'org.greenrobot:eventbus-annotation-processor:3.0.1'

    這裏需要注意,如果應用了EventBusAnnotationProcessor卻沒有設置arguments的話,編譯時就會報錯:
    No option eventBusIndex passed to annotation processor

    此時需要我們先編譯一次,生成索引類。編譯成功之後,就會發現在\ProjectName\app\build\generated\source\apt\PakageName\下看到通過註解分析生成的索引類,這樣我們便可以在初始化EventBus時應用我們生成的索引了。

  • 2.2 初始化EventBus

    EventBus默認有一個單例,可以通過getDefault()獲取,也可以通過EventBus.builder()構造自定義的EventBus,比如要應用我們生成好的索引時:

    EventBus mEventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();

    如果想把自定義的設置應用到EventBus默認的單例中,則可以用installDefaultEventBus()方法:

    EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
  • 2.3 註冊訂閱者(監聽事件)
    首先我們需要將我們希望訂閱事件的類,通過EventBus類註冊,註冊代碼如下:

    EventBus.getDefault().register(this);
  • 2.4 編寫訂閱方法
    註冊之後,我們需要編寫響應事件的方法,代碼如下:

    @Subscribe(threadMode = ThreadMode.BACKGROUND, sticky = true, priority = 100)
    public void test(String str) {
    
    }

    註解有三個參數,threadMode爲回調所在的線程,priority爲優先級,sticky爲是否接收黏性事件。調度單位從類細化到了方法,對方法的命名也沒有了要求,方便混淆代碼。但註冊了監聽的模塊必須有一個標註了Subscribe註解方法,不然在register時會拋出異常:

    Subscriber class XXX and its super classes have no public methods with the @Subscribe annotation
  • 2.5 發送事件

    調用post或者postSticky即可:

    EventBus.getDefault().post("str");
    EventBus.getDefault().postSticky("str");
  • 2.6 解除註冊

    EventBus.getDefault().unregister(this);

3.原理分析

先來看一看核心架構
這裏寫圖片描述

核心類圖

這裏寫圖片描述

帶有索引加速的核心類圖
這裏寫圖片描述

先看核心類EventBus,其中subscriptionByEventType是以事件的類爲key,訂閱者的回調方法爲value的映射關係表。也就是說EventBus在收到一個事件時,就可以根據這個事件的類型,在subscriptionByEventType中找到所有監聽了該事件的訂閱者及處理事件的回調方法。而typesBySubscriber則是每個訂閱者所監聽的事件類型表,在取消註冊時可以通過該表中保存的信息,快速刪除subscriptionByEventType中訂閱者的註冊信息,避免遍歷查找。註冊事件、發送事件和註銷都是圍繞着這兩個核心數據結構來展開。上面的Subscription可以理解爲每個訂閱者與回調方法的關係,在其他模塊發送事件時,就會通過這個關係,讓訂閱者執行回調方法。

回調方法在這裏被封裝成了SubscriptionMethod,裏面保存了在需要反射invoke方法時的各種參數,包括優先級,是否接收黏性事件和所在線程等信息。而要生成這些封裝好的方法,則需要SubscriberMethodFinder,它可以在regster時得到訂閱者的所有回調方法,並封裝返回給EventBus。而右邊的加速器模塊,就是爲了提高SubscriberMethodFinder的效率,會在第三章詳細介紹,這裏就不再囉嗦。

而下面的三個Poster,則是EventBus能在不同的線程執行回調方法的核心,我們根據不同的回調方式來看:

  1. POSTING(在調用post所在的線程執行回調):不需要poster來調度,直接運行。
  2. MAIN(在UI線程回調):如果post所在線程爲UI線程則直接執行,否則則通過mainThreadPoster來調度。
  3. BACKGROUND(在Backgroud線程回調):如果post所在線程爲非UI線程則直接執行,否則則通過backgroundPoster來調度。
  4. ASYNC(交給線程池來管理):直接通過asyncPoster調度。

可以看到,不同的Poster會在post事件時,調度相應的事件隊列PendingPostQueue,讓每個訂閱者的回調方法收到相應的事件,並在其註冊的Thread中運行。而這個事件隊列是一個鏈表,由一個個PendingPost組成,其中包含了事件,事件訂閱者,回調方法這三個核心參數,以及需要執行的下一個PendingPost。

至此EventBus 3的架構就分析完了,與之前EventBus老版本最明顯的區別在於:分發事件的調度單位從訂閱者,細化成了訂閱者的回調方法。也就是說每個回調方法都有自己的優先級,執行線程和是否接收黏性事件,提高了事件分發的靈活程度,接下來我們在看核心功能的實現時更能體現這一點。

4.源碼分析

  • 4.1 創建EventBus

    一般情況下我們都是通過EventBus.getDefault()獲取到EventBus對象,從而在進行register()或者post()等等,所以我們看看getDefault()方法的實現:

       /** Convenience singleton for apps using a process-wide EventBus instance. */
        public static EventBus getDefault() {
            if (defaultInstance == null) {
                synchronized (EventBus.class) {
                    if (defaultInstance == null) {
                        defaultInstance = new EventBus();
                    }
                }
            }
            return defaultInstance;
        }

    很明顯這是一個單例模式,採用了雙重檢查模式 (DCL),目的是爲了保證getDefault()得到的都是同一個實例。如果不存在實例,就調用了EventBus的構造方法:

       private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
    
       //key:訂閱的事件,value:訂閱這個事件的所有訂閱者集合
       private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    
       //key:訂閱者對象,value:這個訂閱者訂閱的事件集合
       private final Map<Object, List<Class<?>>> typesBySubscriber;
    
       //粘性事件 key:粘性事件的class對象, value:事件對象
       private final Map<Class<?>, Object> stickyEvents;
    
       public EventBus() {
           this(DEFAULT_BUILDER);
       }
    
       EventBus(EventBusBuilder builder) {
            //key:訂閱的事件,value:訂閱這個事件的所有訂閱者集合
            subscriptionsByEventType = new HashMap<>();
            //key:訂閱者對象,value:這個訂閱者訂閱的事件集合
            typesBySubscriber = new HashMap<>();
            //粘性事件 key:粘性事件的class對象, value:事件對象
            stickyEvents = new ConcurrentHashMap<>();
            //事件主線程處理
            mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
            //事件 Background 處理
            backgroundPoster = new BackgroundPoster(this);
            //事件異步線程處理
            asyncPoster = new AsyncPoster(this);
            indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
            //訂閱者響應函數信息存儲和查找類
            subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                    builder.strictMethodVerification, builder.ignoreGeneratedIndex);
            logSubscriberExceptions = builder.logSubscriberExceptions;
            logNoSubscriberMessages = builder.logNoSubscriberMessages;
            sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
            sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
            throwSubscriberException = builder.throwSubscriberException;
            //是否支持事件繼承
            eventInheritance = builder.eventInheritance;
            executorService = builder.executorService;
       }

    可以看出是通過初始化了一個EventBusBuilder()對象來分別初始化EventBus的一些配置,當我們在寫一個需要自定義配置的框架的時候,這種實現方法非常普遍,將配置解耦出去,使我們的代碼結構更清晰.

  • 4.2 訂閱者註冊(register)
    簡單來說就是:根據訂閱者的類來找回調方法,把訂閱者和回調方法封裝成關係,並保存到相應的數據結構中,爲隨後的事件分發做好準備,最後處理黏性事件:

    4.2.1 register()源碼:

    public void register(Object subscriber) {
        //首先獲得訂閱者的class對象
        Class<?> subscriberClass = subscriber.getClass();
        //通過subscriberMethodFinder來找到訂閱者訂閱了哪些事件.返回一個SubscriberMethod對象的List,SubscriberMethod
        //裏包含了這個方法的Method對象,以及將來響應訂閱是在哪個線程的ThreadMode,以及訂閱                  
        //的事件類型eventType,以及訂閱的優先級priority,以及是否接收粘性sticky事件的
        //boolean值.
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //訂閱
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    可以看到register()方法很簡潔,代碼裏的註釋也很清楚了,我們可以看出通過subscriberMethodFinder.findSubscriberMethods(subscriberClass)方法就能返回一個SubscriberMethod的對象,而SubscriberMethod裏包含了所有我們需要的接下來執行subscribe()的信息.所以我們先去看看findSubscriberMethods()是怎麼實現的,然後我們再去關注subscribe()。

    4.2.2 SubscriberMethodFinder的實現

    findSubscriberMethods找出一個SubscriberMethod的集合,也就是傳進來的訂閱者所有的訂閱的方法,接下來遍歷訂閱者的訂閱方法來完成訂閱者的訂閱操作。對於SubscriberMethod(訂閱方法)類中,主要就是用保存訂閱方法的Method對象、線程模式、事件類型、優先級、是否是粘性事件等屬性。下面就來看一下findSubscriberMethods方法:

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        //先從METHOD_CACHE取看是否有緩存,key:保存訂閱類的類名,value:保存類中訂閱的方法數據,
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        //是否忽略註解器生成的MyEventBusIndex類
        if (ignoreGeneratedIndex) {
            //利用反射來讀取訂閱類中的訂閱方法信息
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            //從註解器生成的MyEventBusIndex類中獲得訂閱類的訂閱方法信息
            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緩存
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

    首先從緩存中查找,如果找到了就立馬返回。如果緩存中沒有的話,則根據 ignoreGeneratedIndex 選擇如何查找訂閱方法,ignoreGeneratedIndex屬性表示是否忽略註解器生成的MyEventBusIndex。(關於這個MyEventBusIndex需要單獨引入apt組件) 最後,找到訂閱方法後,放入緩存,以免下次繼續查找。ignoreGeneratedIndex 默認就是false,可以通過EventBusBuilder來設置它的值。我們在項目中經常通過EventBus單例模式來獲取默認的EventBus對象,也就是ignoreGeneratedIndex爲false的情況,這種情況調用了findUsingInfo方法:

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            //獲取訂閱者信息,沒有配置MyEventBusIndex返回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 {
                //通過反射來查找訂閱方法
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

通過getSubscriberInfo方法來獲取訂閱者信息。在我們開始查找訂閱方法的時候並沒有忽略註解器爲我們生成的索引MyEventBusIndex,如果我們通過EventBusBuilder配置了MyEventBusIndex,便會獲取到subscriberInfo,調用subscriberInfo的getSubscriberMethods方法便可以得到訂閱方法相關的信息,這個時候就不在需要通過註解進行獲取訂閱方法。如果沒有配置MyEventBusIndex,便會執行findUsingReflectionInSingleClass方法,將訂閱方法保存到findState中。最後再通過getMethodsAndRelease方法對findState做回收處理並反回訂閱方法的List集合。
MyEventBusIndex是一個可選項,主要用來加速獲取事件方法的一個類,下面就來看一下這個類:

/** This class is generated by EventBus, do not edit. */
public class MyEventBusIndex implements SubscriberInfoIndex {
    private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;

    static {
        SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();

        putIndex(new SimpleSubscriberInfo(com.headfirst.demo.WeatherData.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("onDemo", com.headfirst.demo.Display3.class, ThreadMode.POSTING, 1, true),
        }));

        putIndex(new SimpleSubscriberInfo(com.headfirst.demo.Display1.class, true, new SubscriberMethodInfo[] {
            new SubscriberMethodInfo("ontest", String.class),
        }));

    }

    private static void putIndex(SubscriberInfo info) {
        SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
    }

    @Override
    public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
        SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
        if (info != null) {
            return info;
        } else {
            return null;
        }
    }
}

可以看出是使用一個靜態HashMap即:SUBSCRIBER_INDEX來保存訂閱類的信息,其中包括了訂閱類的class對象,是否需要檢查父類,以及訂閱方法的信息SubscriberMethodInfo的數組,SubscriberMethodInfo中又保存了,訂閱方法的方法名,訂閱的事件類型,觸發線程,是否接收sticky事件以及優先級priority.這其中就保存了register()的所有需要的信息,如果再配置EventBus的時候通過EventBusBuilder配置:eventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();來將編譯生成的MyEventBusIndex配置進去,這樣就能在SubscriberMethodFinder類中直接查找出訂閱類的信息,就不需要再利用註解判斷了,當然這種方法是作爲EventBus的可選配置,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;
    }
    //遍歷Method
    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 subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    Class<?> eventType = parameterTypes[0];
                    //校驗是否添加該方法
                    if (findState.checkAdd(method, eventType)) {
                        ThreadMode threadMode = subscribeAnnotation.threadMode();
                        //實例化SubscriberMethod對象並添加
                        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");
        }
    }
}

在這裏主要是使用了Java的反射和對註解的解析。首先通過反射來獲取訂閱者中所有的方法。並根據方法的類型,參數和註解來找到訂閱方法。找到訂閱方法後將訂閱方法相關信息保存到FindState當中。最後再通過getMethodsAndRelease()返回List,findState.recycle()複用findState對象。至此,所有關於如何獲得訂閱類的訂閱方法信息即:SubscriberMethod對象就已經完全分析完了,下面我們來看subscribe()是如何實現的.

4.2.3 subscribe()源碼:

//必須在同步代碼塊裏調用
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //獲取訂閱的事件類型
    Class<?> eventType = subscriberMethod.eventType;
    //創建Subscription對象
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //從subscriptionsByEventType裏檢查是否已經添加過該Subscription,如果添加過就拋出異常
    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);
        }
    }
    //根據優先級priority來添加Subscription對象
    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裏.
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);
    //如果接收sticky事件,立即分發sticky事件
    if (subscriberMethod.sticky) {
        //eventInheritance 表示是否分發訂閱了響應事件類父類事件的方法
        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 {
            Object stickyEvent = stickyEvents.get(eventType);
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

上面是ignoreGeneratedIndex爲false的情況,當配置ignoreGeneratedIndex爲true時:

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
    //FindState 用來做訂閱方法的校驗和保存
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    while (findState.clazz != null) {
        //通過反射來獲得訂閱方法信息
        findUsingReflectionInSingleClass(findState);
        //查找父類的訂閱方法
        findState.moveToSuperclass();
    }
    //獲取findState中的SubscriberMethod(也就是訂閱方法List)並返回
    return getMethodsAndRelease(findState);
}

然後在這個方法裏面會調用findUsingReflectionInSingleClass方法通過反射方式獲取訂閱者的回調方法。

下面來看一個這個註冊過程的流程圖:
這裏寫圖片描述

  • 4.3 事件的發送(post)
    獲取到默認的EventBus的默認對象來發送事件
public void post(Object event) {
    //得到當前線程的Posting狀態.
    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;
        }
    }

首先是通過currentPostingThreadState.get()方法來得到當前線程PostingThreadState的對象,爲什麼是說當前線程我們來看看currentPostingThreadState的實現:

private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
    @Override
    protected PostingThreadState initialValue() {
        return new PostingThreadState();
    }
};

currentPostingThreadState的實現是一個包含了PostingThreadState的ThreadLocal對象,關於ThreadLocal
張濤的這篇文章解釋的很好:ThreadLocal 是一個線程內部的數據存儲類,通過它可以在指定的線程中存儲數據,
而這段數據是不會與其他線程共享的。其內部原理是通過生成一個它包裹的泛型對象的數組,在不同的線程會有不同的數組索引值,通過這樣就可以做到每個線程通過get() 方法獲取的時候,取到的只能是自己線程所對應的數據。 所以這裏取到的就是每個線程的PostingThreadState狀態.接下來我們來看postSingleEvent()方法

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    //是否觸發訂閱了該事件(eventClass)的父類,以及接口的類的響應方法.
    if (eventInheritance) {
        //查找eventClass類所有的父類以及接口
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        //循環postSingleEventForEventType
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);
            //只要右邊有一個爲true,subscriptionFound就爲true
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
        //post單個
        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) {
            //發送一個NoSubscriberEvent事件,如果我們需要處理這種狀態,接收這個事件就可以了
            post(new NoSubscriberEvent(this, event));
        }
    }
}

跟着上面的代碼的註釋,我們可以很清楚的發現是在postSingleEventForEventType()方法裏去進行事件的分發,代碼如下:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
    CopyOnWriteArrayList<Subscription> subscriptions;
    //獲取訂閱了這個事件的Subscription列表.
    synchronized (this) {
        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;
            } finally {
                postingState.event = null;
                postingState.subscription = null;
                postingState.canceled = false;
            }
            if (aborted) {
                break;
            }
        }
        return true;
    }
    return false;
}

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);
    }

總結上面的代碼就是,首先從subscriptionsByEventType裏獲得所有訂閱了這個事件的Subscription列表,然後在通過postToSubscription()方法來分發事件,在postToSubscription()通過不同的threadMode在不同的線程裏invoke()訂閱者的方法,ThreadMode共有四類:

1.PostThread:默認的 ThreadMode,表示在執行 Post 操作的線程直接調用訂閱者的事件響應方法,不論該線程是否爲主線程(UI 線程)。當該線程爲主線程時,響應方法中不能有耗時操作,否則有卡主線程的風險。適用場景:對於是否在主線程執行無要求,但若 Post 線程爲主線程,不能耗時的操作;

2.MainThread:在主線程中執行響應方法。如果發佈線程就是主線程,則直接調用訂閱者的事件響應方法,否則通過主線程的 Handler 發送消息在主線程中處理——調用訂閱者的事件響應函數。顯然,MainThread類的方法也不能有耗時操作,以避免卡主線程。適用場景:必須在主線程執行的操作;

3.BackgroundThread:在後臺線程中執行響應方法。如果發佈線程不是主線程,則直接調用訂閱者的事件響應函數,否則啓動唯一的後臺線程去處理。由於後臺線程是唯一的,當事件超過一個的時候,它們會被放在隊列中依次執行,因此該類響應方法雖然沒有PostThread類和MainThread類方法對性能敏感,但最好不要有重度耗時的操作或太頻繁的輕度耗時操作,以造成其他操作等待。適用場景:操作輕微耗時且不會過於頻繁,即一般的耗時操作都可以放在這裏;

4.Async:不論發佈線程是否爲主線程,都使用一個空閒線程來處理。和BackgroundThread不同的是,Async類的所有線程是相互獨立的,因此不會出現卡線程的問題。適用場景:長耗時操作,例如網絡訪問。

invokeSubscriber(subscription, event);代碼如下:

   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);
        }
    }

總的來說就是分析事件,得到所有監聽該事件的訂閱者的回調方法,並利用反射來invoke方法,實現回調

這裏寫圖片描述

  • 4.3 解除註冊源碼(unregister)

相對於上面的註冊和發送事件,解除註冊要簡單很多,實現如下:

/** Unregisters the given subscriber from all event classes. */
public synchronized void unregister(Object subscriber) {
    //通過typesBySubscriber來取出這個subscriber訂閱者訂閱的事件類型,
    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
    if (subscribedTypes != null) {
        //分別解除每個訂閱了的事件類型
        for (Class<?> eventType : subscribedTypes) {
            unsubscribeByEventType(subscriber, eventType);
        }
        //從typesBySubscriber移除subscriber
        typesBySubscriber.remove(subscriber);
    } else {
        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
    }
}

然後接着看unsubscribeByEventType()方法的實現:

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
    //subscriptionsByEventType裏拿出這個事件類型的訂閱者列表.
    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--;
            }
        }
    }
}

最終分別從typesBySubscriber和subscriptions裏分別移除訂閱者以及相關信息即可.

這裏寫圖片描述

5.設計模式

觀察者模式觀察者模式是對象的行爲模式,又叫發佈-訂閱(Publish/Subscribe)模式、模型-視圖(Model/View)模式、源-監聽器(Source/Listener)模式或從屬者(Dependents)模式。觀察者模式定義了一種一對多的依賴關係,讓多個觀察者對象同時監聽某一個主題對象。這個主題對象在狀態上發生變化時,會通知所有觀察者對象,使它們能夠自動更新自己。EventBus並不是標準的觀察者模式的實現,但是它的整體就是一個發佈/訂閱框架,也擁有觀察者模式的優點,比如:發佈者和訂閱者的解耦.

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