Android EventBus源碼解析 帶你深入理解EventBus

轉載請標明出處:http://blog.csdn.net/lmj623565791/article/details/40920453,本文出自:【張鴻洋的博客】

上一篇帶大家初步瞭解了EventBus的使用方式,詳見:Android EventBus實戰 沒聽過你就out了,本篇博客將解析EventBus的源碼,相信能夠讓大家深入理解該框架的實現,也能解決很多在使用中的疑問:爲什麼可以這麼做?爲什麼這麼做不好呢?

1、概述

一般使用EventBus的組件類,類似下面這種方式:

  1. public class SampleComponent extends Fragment  
  2. {  
  3.   
  4.     @Override  
  5.     public void onCreate(Bundle savedInstanceState)  
  6.     {  
  7.         super.onCreate(savedInstanceState);  
  8.         EventBus.getDefault().register(this);  
  9.     }  
  10.   
  11.     public void onEventMainThread(param)  
  12.     {  
  13.     }  
  14.       
  15.     public void onEventPostThread(param)  
  16.     {  
  17.           
  18.     }  
  19.       
  20.     public void onEventBackgroundThread(param)  
  21.     {  
  22.           
  23.     }  
  24.       
  25.     public void onEventAsync(param)  
  26.     {  
  27.           
  28.     }  
  29.       
  30.     @Override  
  31.     public void onDestroy()  
  32.     {  
  33.         super.onDestroy();  
  34.         EventBus.getDefault().unregister(this);  
  35.     }  
  36.       
  37. }  
public class SampleComponent extends Fragment
{

    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    public void onEventMainThread(param)
    {
    }

    public void onEventPostThread(param)
    {

    }

    public void onEventBackgroundThread(param)
    {

    }

    public void onEventAsync(param)
    {

    }

    @Override
    public void onDestroy()
    {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

}

大多情況下,都會在onCreate中進行register,在onDestory中進行unregister ;

看完代碼大家或許會有一些疑問:

1、代碼中還有一些以onEvent開頭的方法,這些方法是幹嘛的呢?

在回答這個問題之前,我有一個問題,你咋不問register(this)是幹嘛的呢?其實register(this)就是去當前類,遍歷所有的方法,找到onEvent開頭的然後進行存儲。現在知道onEvent開頭的方法是幹嘛的了吧。

2、那onEvent後面的那些MainThread應該是什麼標誌吧?

嗯,是的,onEvent後面可以寫四種,也就是上面出現的四個方法,決定了當前的方法最終在什麼線程運行,怎麼運行,可以參考上一篇博客或者細細往下看。


既然register了,那麼肯定得說怎麼調用是吧。

  1. EventBus.getDefault().post(param);  
EventBus.getDefault().post(param);

調用很簡單,一句話,你也可以叫發佈,只要把這個param發佈出去,EventBus會在它內部存儲的方法中,進行掃描,找到參數匹配的,就使用反射進行調用。

現在有沒有覺得,撇開專業術語:其實EventBus就是在內部存儲了一堆onEvent開頭的方法,然後post的時候,根據post傳入的參數,去找到匹配的方法,反射調用之。

那麼,我告訴你,它內部使用了Map進行存儲,鍵就是參數的Class類型。知道是這個類型,那麼你覺得根據post傳入的參數進行查找還是個事麼?


下面我們就去看看EventBus的register和post真面目。

2、register

EventBus.getDefault().register(this);

首先:

EventBus.getDefault()其實就是個單例,和我們傳統的getInstance一個意思:

  1. /** Convenience singleton for apps using a process-wide EventBus instance. */  
  2.    public static EventBus getDefault() {  
  3.        if (defaultInstance == null) {  
  4.            synchronized (EventBus.class) {  
  5.                if (defaultInstance == null) {  
  6.                    defaultInstance = new EventBus();  
  7.                }  
  8.            }  
  9.        }  
  10.        return defaultInstance;  
  11.    }  
 /** 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;
    }

使用了雙重判斷的方式,防止併發的問題,還能極大的提高效率。

然後register應該是一個普通的方法,我們去看看:

register公佈給我們使用的有4個:

  1.  public void register(Object subscriber) {  
  2.         register(subscriber, DEFAULT_METHOD_NAME, false0);  
  3.     }  
  4.  public void register(Object subscriber, int priority) {  
  5.         register(subscriber, DEFAULT_METHOD_NAME, false, priority);  
  6.     }  
  7. public void registerSticky(Object subscriber) {  
  8.         register(subscriber, DEFAULT_METHOD_NAME, true0);  
  9.     }  
  10. public void registerSticky(Object subscriber, int priority) {  
  11.         register(subscriber, DEFAULT_METHOD_NAME, true, priority);  
  12.     }  
 public void register(Object subscriber) {
        register(subscriber, DEFAULT_METHOD_NAME, false, 0);
    }
 public void register(Object subscriber, int priority) {
        register(subscriber, DEFAULT_METHOD_NAME, false, priority);
    }
public void registerSticky(Object subscriber) {
        register(subscriber, DEFAULT_METHOD_NAME, true, 0);
    }
public void registerSticky(Object subscriber, int priority) {
        register(subscriber, DEFAULT_METHOD_NAME, true, priority);
    }

本質上就調用了同一個:

  1. private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) {  
  2.         List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),  
  3.                 methodName);  
  4.         for (SubscriberMethod subscriberMethod : subscriberMethods) {  
  5.             subscribe(subscriber, subscriberMethod, sticky, priority);  
  6.         }  
  7.     }  
private synchronized void register(Object subscriber, String methodName, boolean sticky, int priority) {
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),
                methodName);
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod, sticky, priority);
        }
    }

四個參數

subscriber 是我們掃描類的對象,也就是我們代碼中常見的this;

methodName 這個是寫死的:“onEvent”,用於確定掃描什麼開頭的方法,可見我們的類中都是以這個開頭。

sticky 這個參數,解釋源碼的時候解釋,暫時不用管

priority 優先級,優先級越高,在調用的時候會越先調用。

下面開始看代碼:

  1. List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),  
  2.                 methodName);  
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriber.getClass(),
                methodName);

調用內部類SubscriberMethodFinder的findSubscriberMethods方法,傳入了subscriber 的class,以及methodName,返回一個List<SubscriberMethod>。

那麼不用說,肯定是去遍歷該類內部所有方法,然後根據methodName去匹配,匹配成功的封裝成SubscriberMethod,最後返回一個List。下面看代碼:

  1. List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, String eventMethodName) {  
  2.         String key = subscriberClass.getName() + ’.’ + eventMethodName;  
  3.         List<SubscriberMethod> subscriberMethods;  
  4.         synchronized (methodCache) {  
  5.             subscriberMethods = methodCache.get(key);  
  6.         }  
  7.         if (subscriberMethods != null) {  
  8.             return subscriberMethods;  
  9.         }  
  10.         subscriberMethods = new ArrayList<SubscriberMethod>();  
  11.         Class<?> clazz = subscriberClass;  
  12.         HashSet<String> eventTypesFound = new HashSet<String>();  
  13.         StringBuilder methodKeyBuilder = new StringBuilder();  
  14.         while (clazz != null) {  
  15.             String name = clazz.getName();  
  16.             if (name.startsWith(“java.”) || name.startsWith(“javax.”) || name.startsWith(“android.”)) {  
  17.                 // Skip system classes, this just degrades performance  
  18.                 break;  
  19.             }  
  20.   
  21.             // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)  
  22.             Method[] methods = clazz.getMethods();  
  23.             for (Method method : methods) {  
  24.                 String methodName = method.getName();  
  25.                 if (methodName.startsWith(eventMethodName)) {  
  26.                     int modifiers = method.getModifiers();  
  27.                     if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {  
  28.                         Class<?>[] parameterTypes = method.getParameterTypes();  
  29.                         if (parameterTypes.length == 1) {  
  30.                             String modifierString = methodName.substring(eventMethodName.length());  
  31.                             ThreadMode threadMode;  
  32.                             if (modifierString.length() == 0) {  
  33.                                 threadMode = ThreadMode.PostThread;  
  34.                             } else if (modifierString.equals(“MainThread”)) {  
  35.                                 threadMode = ThreadMode.MainThread;  
  36.                             } else if (modifierString.equals(“BackgroundThread”)) {  
  37.                                 threadMode = ThreadMode.BackgroundThread;  
  38.                             } else if (modifierString.equals(“Async”)) {  
  39.                                 threadMode = ThreadMode.Async;  
  40.                             } else {  
  41.                                 if (skipMethodVerificationForClasses.containsKey(clazz)) {  
  42.                                     continue;  
  43.                                 } else {  
  44.                                     throw new EventBusException(“Illegal onEvent method, check for typos: ” + method);  
  45.                                 }  
  46.                             }  
  47.                             Class<?> eventType = parameterTypes[0];  
  48.                             methodKeyBuilder.setLength(0);  
  49.                             methodKeyBuilder.append(methodName);  
  50.                             methodKeyBuilder.append(’>’).append(eventType.getName());  
  51.                             String methodKey = methodKeyBuilder.toString();  
  52.                             if (eventTypesFound.add(methodKey)) {  
  53.                                 // Only add if not already found in a sub class  
  54.                                 subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));  
  55.                             }  
  56.                         }  
  57.                     } else if (!skipMethodVerificationForClasses.containsKey(clazz)) {  
  58.                         Log.d(EventBus.TAG, ”Skipping method (not public, static or abstract): ” + clazz + “.”  
  59.                                 + methodName);  
  60.                     }  
  61.                 }  
  62.             }  
  63.             clazz = clazz.getSuperclass();  
  64.         }  
  65.         if (subscriberMethods.isEmpty()) {  
  66.             throw new EventBusException(“Subscriber ” + subscriberClass + “ has no public methods called ”  
  67.                     + eventMethodName);  
  68.         } else {  
  69.             synchronized (methodCache) {  
  70.                 methodCache.put(key, subscriberMethods);  
  71.             }  
  72.             return subscriberMethods;  
  73.         }  
  74.     }  
List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass, String eventMethodName) {
        String key = subscriberClass.getName() + '.' + eventMethodName;
        List<SubscriberMethod> subscriberMethods;
        synchronized (methodCache) {
            subscriberMethods = methodCache.get(key);
        }
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        subscriberMethods = new ArrayList<SubscriberMethod>();
        Class<?> clazz = subscriberClass;
        HashSet<String> eventTypesFound = new HashSet<String>();
        StringBuilder methodKeyBuilder = new StringBuilder();
        while (clazz != null) {
            String name = clazz.getName();
            if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
                // Skip system classes, this just degrades performance
                break;
            }

            // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
            Method[] methods = clazz.getMethods();
            for (Method method : methods) {
                String methodName = method.getName();
                if (methodName.startsWith(eventMethodName)) {
                    int modifiers = method.getModifiers();
                    if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                        Class<?>[] parameterTypes = method.getParameterTypes();
                        if (parameterTypes.length == 1) {
                            String modifierString = methodName.substring(eventMethodName.length());
                            ThreadMode threadMode;
                            if (modifierString.length() == 0) {
                                threadMode = ThreadMode.PostThread;
                            } else if (modifierString.equals("MainThread")) {
                                threadMode = ThreadMode.MainThread;
                            } else if (modifierString.equals("BackgroundThread")) {
                                threadMode = ThreadMode.BackgroundThread;
                            } else if (modifierString.equals("Async")) {
                                threadMode = ThreadMode.Async;
                            } else {
                                if (skipMethodVerificationForClasses.containsKey(clazz)) {
                                    continue;
                                } else {
                                    throw new EventBusException("Illegal onEvent method, check for typos: " + method);
                                }
                            }
                            Class<?> eventType = parameterTypes[0];
                            methodKeyBuilder.setLength(0);
                            methodKeyBuilder.append(methodName);
                            methodKeyBuilder.append('>').append(eventType.getName());
                            String methodKey = methodKeyBuilder.toString();
                            if (eventTypesFound.add(methodKey)) {
                                // Only add if not already found in a sub class
                                subscriberMethods.add(new SubscriberMethod(method, threadMode, eventType));
                            }
                        }
                    } else if (!skipMethodVerificationForClasses.containsKey(clazz)) {
                        Log.d(EventBus.TAG, "Skipping method (not public, static or abstract): " + clazz + "."
                                + methodName);
                    }
                }
            }
            clazz = clazz.getSuperclass();
        }
        if (subscriberMethods.isEmpty()) {
            throw new EventBusException("Subscriber " + subscriberClass + " has no public methods called "
                    + eventMethodName);
        } else {
            synchronized (methodCache) {
                methodCache.put(key, subscriberMethods);
            }
            return subscriberMethods;
        }
    }
呵,代碼還真長;不過我們直接看核心部分:

22行:看到沒,clazz.getMethods();去得到所有的方法:

23-62行:就開始遍歷每一個方法了,去匹配封裝了。

25-29行:分別判斷了是否以onEvent開頭,是否是public且非static和abstract方法,是否是一個參數。如果都複合,才進入封裝的部分。

32-45行:也比較簡單,根據方法的後綴,來確定threadMode,threadMode是個枚舉類型:就四種情況。

最後在54行:將method, threadMode, eventType傳入構造了:new SubscriberMethod(method, threadMode, eventType)。添加到List,最終放回。

注意下63行:clazz = clazz.getSuperclass();可以看到,會掃描所有的父類,不僅僅是當前類。

繼續回到register:

  1. for (SubscriberMethod subscriberMethod : subscriberMethods) {  
  2.             subscribe(subscriber, subscriberMethod, sticky, priority);  
  3.         }  
for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod, sticky, priority);
        }

for循環掃描到的方法,然後去調用suscribe方法。

  1. // Must be called in synchronized block  
  2.    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {  
  3.        subscribed = true;  
  4.        Class<?> eventType = subscriberMethod.eventType;  
  5.        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);  
  6.        Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);  
  7.        if (subscriptions == null) {  
  8.            subscriptions = new CopyOnWriteArrayList<Subscription>();  
  9.            subscriptionsByEventType.put(eventType, subscriptions);  
  10.        } else {  
  11.            for (Subscription subscription : subscriptions) {  
  12.                if (subscription.equals(newSubscription)) {  
  13.                    throw new EventBusException(“Subscriber ” + subscriber.getClass() + “ already registered to event ”  
  14.                            + eventType);  
  15.                }  
  16.            }  
  17.        }  
  18.   
  19.        // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)  
  20.        // subscriberMethod.method.setAccessible(true);  
  21.   
  22.        int size = subscriptions.size();  
  23.        for (int i = 0; i <= size; i++) {  
  24.            if (i == size || newSubscription.priority > subscriptions.get(i).priority) {  
  25.                subscriptions.add(i, newSubscription);  
  26.                break;  
  27.            }  
  28.        }  
  29.   
  30.        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);  
  31.        if (subscribedEvents == null) {  
  32.            subscribedEvents = new ArrayList<Class<?>>();  
  33.            typesBySubscriber.put(subscriber, subscribedEvents);  
  34.        }  
  35.        subscribedEvents.add(eventType);  
  36.   
  37.        if (sticky) {  
  38.            Object stickyEvent;  
  39.            synchronized (stickyEvents) {  
  40.                stickyEvent = stickyEvents.get(eventType);  
  41.            }  
  42.            if (stickyEvent != null) {  
  43.                // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)  
  44.                // –> Strange corner case, which we don’t take care of here.  
  45.                postToSubscription(newSubscription, stickyEvent, Looper.getMainLooper() == Looper.myLooper());  
  46.            }  
  47.        }  
  48.    }  
 // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod, boolean sticky, int priority) {
        subscribed = true;
        Class<?> eventType = subscriberMethod.eventType;
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod, priority);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<Subscription>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            for (Subscription subscription : subscriptions) {
                if (subscription.equals(newSubscription)) {
                    throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                            + eventType);
                }
            }
        }

        // Starting with EventBus 2.2 we enforced methods to be public (might change with annotations again)
        // subscriberMethod.method.setAccessible(true);

        int size = subscriptions.size();
        for (int i = 0; i <= size; i++) {
            if (i == size || newSubscription.priority > subscriptions.get(i).priority) {
                subscriptions.add(i, newSubscription);
                break;
            }
        }

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

        if (sticky) {
            Object stickyEvent;
            synchronized (stickyEvents) {
                stickyEvent = stickyEvents.get(eventType);
            }
            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());
            }
        }
    }
我們的subscriberMethod中保存了method, threadMode, eventType,上面已經說了;

4-17行:根據subscriberMethod.eventType,去subscriptionsByEventType去查找一個CopyOnWriteArrayList<Subscription> ,如果沒有則創建。

順便把我們的傳入的參數封裝成了一個:Subscription(subscriber, subscriberMethod, priority);

這裏的subscriptionsByEventType是個Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> ; 這個Map其實就是EventBus存儲方法的地方,一定要記住!

22-28行:實際上,就是添加newSubscription;並且是按照優先級添加的。可以看到,優先級越高,會插到在當前List的前面。

30-35行:根據subscriber存儲它所有的eventType ; 依然是map;key:subscriber ,value:List<eventType> ;知道就行,非核心代碼,主要用於isRegister的判斷。

37-47行:判斷sticky;如果爲true,從stickyEvents中根據eventType去查找有沒有stickyEvent,如果有則立即發佈去執行。stickyEvent其實就是我們post時的參數。

postToSubscription這個方法,我們在post的時候會介紹。


到此,我們register就介紹完了。

你只要記得一件事:掃描了所有的方法,把匹配的方法最終保存在subscriptionsByEventType(Map,key:eventType ; value:CopyOnWriteArrayList<Subscription> )中;

eventType是我們方法參數的Class,Subscription中則保存着subscriber, subscriberMethod(method, threadMode, eventType), priority;包含了執行改方法所需的一切。


3、post

register完畢,知道了EventBus如何存儲我們的方法了,下面看看post它又是如何調用我們的方法的。

再看源碼之前,我們猜測下:register時,把方法存在subscriptionsByEventType;那麼post肯定會去subscriptionsByEventType去取方法,然後調用。

下面看源碼:

  1. /** Posts the given event to the event bus. */  
  2.    public void post(Object event) {  
  3.        PostingThreadState postingState = currentPostingThreadState.get();  
  4.        List<Object> eventQueue = postingState.eventQueue;  
  5.        eventQueue.add(event);  
  6.   
  7.        if (postingState.isPosting) {  
  8.            return;  
  9.        } else {  
  10.            postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();  
  11.            postingState.isPosting = true;  
  12.            if (postingState.canceled) {  
  13.                throw new EventBusException(“Internal error. Abort state was not reset”);  
  14.            }  
  15.            try {  
  16.                while (!eventQueue.isEmpty()) {  
  17.                    postSingleEvent(eventQueue.remove(0), postingState);  
  18.                }  
  19.            } finally {  
  20.                postingState.isPosting = false;  
  21.                postingState.isMainThread = false;  
  22.            }  
  23.        }  
  24.    }  
 /** Posts the given event to the event bus. */
    public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        eventQueue.add(event);

        if (postingState.isPosting) {
            return;
        } else {
            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是一個ThreadLocal類型的,裏面存儲了PostingThreadState;PostingThreadState包含了一個eventQueue和一些標誌位。

  1. private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {  
  2.        @Override  
  3.        protected PostingThreadState initialValue() {  
  4.            return new PostingThreadState();  
  5.        }  
  6.    }  
 private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    }

把我們傳入的event,保存到了當前線程中的一個變量PostingThreadState的eventQueue中。

10行:判斷當前是否是UI線程。

16-18行:遍歷隊列中的所有的event,調用postSingleEvent(eventQueue.remove(0), postingState)方法。

這裏大家會不會有疑問,每次post都會去調用整個隊列麼,那麼不會造成方法多次調用麼?

可以看到第7-8行,有個判斷,就是防止該問題的,isPosting=true了,就不會往下走了。


下面看postSingleEvent

  1. private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {  
  2.         Class<? extends Object> eventClass = event.getClass();  
  3.         List<Class<?>> eventTypes = findEventTypes(eventClass);  
  4.         boolean subscriptionFound = false;  
  5.         int countTypes = eventTypes.size();  
  6.         for (int h = 0; h < countTypes; h++) {  
  7.             Class<?> clazz = eventTypes.get(h);  
  8.             CopyOnWriteArrayList<Subscription> subscriptions;  
  9.             synchronized (this) {  
  10.                 subscriptions = subscriptionsByEventType.get(clazz);  
  11.             }  
  12.             if (subscriptions != null && !subscriptions.isEmpty()) {  
  13.                 for (Subscription subscription : subscriptions) {  
  14.                     postingState.event = event;  
  15.                     postingState.subscription = subscription;  
  16.                     boolean aborted = false;  
  17.                     try {  
  18.                         postToSubscription(subscription, event, postingState.isMainThread);  
  19.                         aborted = postingState.canceled;  
  20.                     } finally {  
  21.                         postingState.event = null;  
  22.                         postingState.subscription = null;  
  23.                         postingState.canceled = false;  
  24.                     }  
  25.                     if (aborted) {  
  26.                         break;  
  27.                     }  
  28.                 }  
  29.                 subscriptionFound = true;  
  30.             }  
  31.         }  
  32.         if (!subscriptionFound) {  
  33.             Log.d(TAG, ”No subscribers registered for event ” + eventClass);  
  34.             if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) {  
  35.                 post(new NoSubscriberEvent(this, event));  
  36.             }  
  37.         }  
  38.     }  
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<? extends Object> eventClass = event.getClass();
        List<Class<?>> eventTypes = findEventTypes(eventClass);
        boolean subscriptionFound = false;
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);
            CopyOnWriteArrayList<Subscription> subscriptions;
            synchronized (this) {
                subscriptions = subscriptionsByEventType.get(clazz);
            }
            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;
                    }
                }
                subscriptionFound = true;
            }
        }
        if (!subscriptionFound) {
            Log.d(TAG, "No subscribers registered for event " + eventClass);
            if (eventClass != NoSubscriberEvent.class && eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

將我們的event,即post傳入的實參;以及postingState傳入到postSingleEvent中。

2-3行:根據event的Class,去得到一個List<Class<?>>;其實就是得到event當前對象的Class,以及父類和接口的Class類型;主要用於匹配,比如你傳入Dog extends Dog,他會把Animal也裝到該List中。

6-31行:遍歷所有的Class,到subscriptionsByEventType去查找subscriptions;哈哈,熟不熟悉,還記得我們register裏面把方法存哪了不?

是不是就是這個Map;

12-30行:遍歷每個subscription,依次去調用postToSubscription(subscription, event, postingState.isMainThread);
這個方法就是去反射執行方法了,大家還記得在register,if(sticky)時,也會去執行這個方法。

下面看它如何反射執行:

  1. private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {  
  2.         switch (subscription.subscriberMethod.threadMode) {  
  3.         case PostThread:  
  4.             invokeSubscriber(subscription, event);  
  5.             break;  
  6.         case MainThread:  
  7.             if (isMainThread) {  
  8.                 invokeSubscriber(subscription, event);  
  9.             } else {  
  10.                 mainThreadPoster.enqueue(subscription, event);  
  11.             }  
  12.             break;  
  13.         case BackgroundThread:  
  14.             if (isMainThread) {  
  15.                 backgroundPoster.enqueue(subscription, event);  
  16.             } else {  
  17.                 invokeSubscriber(subscription, event);  
  18.             }  
  19.             break;  
  20.         case Async:  
  21.             asyncPoster.enqueue(subscription, event);  
  22.             break;  
  23.         default:  
  24.             throw new IllegalStateException(“Unknown thread mode: ” + subscription.subscriberMethod.threadMode);  
  25.         }  
  26.     }  
private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        switch (subscription.subscriberMethod.threadMode) {
        case PostThread:
            invokeSubscriber(subscription, event);
            break;
        case MainThread:
            if (isMainThread) {
                invokeSubscriber(subscription, event);
            } else {
                mainThreadPoster.enqueue(subscription, event);
            }
            break;
        case BackgroundThread:
            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);
        }
    }
前面已經說過subscription包含了所有執行需要的東西,大致有:subscriber, subscriberMethod(method, threadMode, eventType), priority;

那麼這個方法:第一步根據threadMode去判斷應該在哪個線程去執行該方法;
case PostThread:

  1. void invokeSubscriber(Subscription subscription, Object event) throws Error {  
  2.           subscription.subscriberMethod.method.invoke(subscription.subscriber, event);  
  3. }  
  void invokeSubscriber(Subscription subscription, Object event) throws Error {
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
  }

直接反射調用;也就是說在當前的線程直接調用該方法;

case MainThread:

首先去判斷當前如果是UI線程,則直接調用;否則: mainThreadPoster.enqueue(subscription, event);把當前的方法加入到隊列,然後直接通過handler去發送一個消息,在handler的handleMessage中,去執行我們的方法。說白了就是通過Handler去發送消息,然後執行的。

 case BackgroundThread:

如果當前非UI線程,則直接調用;如果是UI線程,則將任務加入到後臺的一個隊列,最終由Eventbus中的一個線程池去調用

executorService = Executors.newCachedThreadPool();。

 case Async:將任務加入到後臺的一個隊列,最終由Eventbus中的一個線程池去調用;線程池與BackgroundThread用的是同一個。

這麼說BackgroundThread和Async有什麼區別呢?

BackgroundThread中的任務,一個接着一個去調用,中間使用了一個布爾型變量handlerActive進行的控制。

Async則會動態控制併發。


到此,我們完整的源碼分析就結束了,總結一下:register會把當前類中匹配的方法,存入一個map,而post會根據實參去map查找進行反射調用。分析這麼久,一句話就說完了~~

其實不用發佈者,訂閱者,事件,總線這幾個詞或許更好理解,以後大家問了EventBus,可以說,就是在一個單例內部維持着一個map對象存儲了一堆的方法;post無非就是根據參數去查找方法,進行反射調用。


4、其餘方法

介紹了register和post;大家獲取還能想到一個詞sticky,在register中,如何sticky爲true,會去stickyEvents去查找事件,然後立即去post;

那麼這個stickyEvents何時進行保存事件呢?

其實evevntbus中,除了post發佈事件,還有一個方法也可以:

  1. public void postSticky(Object event) {  
  2.        synchronized (stickyEvents) {  
  3.            stickyEvents.put(event.getClass(), event);  
  4.        }  
  5.        // Should be posted after it is putted, in case the subscriber wants to remove immediately  
  6.        post(event);  
  7.    }  
 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);
    }

和post功能類似,但是會把方法存儲到stickyEvents中去;

大家再去看看EventBus中所有的public方法,無非都是一些狀態判斷,獲取事件,移除事件的方法;沒什麼好介紹的,基本見名知意。


好了,到此我們的源碼解析就結束了,希望大家不僅能夠了解這些優秀框架的內部機理,更能夠體會到這些框架的很多細節之處,併發的處理,很多地方,爲什麼它這麼做等等。




建了一個QQ羣,方便大家交流。羣號:55032675

———————————————————————————————————-

博主部分視頻已經上線,如果你不喜歡枯燥的文本,請猛戳(初錄,期待您的支持):

1、高仿微信5.2.1主界面及消息提醒

2、高仿QQ5.0側滑

3、Android智能機器人“小慕”的實現



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