1. 程式人生 > >EventBus原始碼分析

EventBus原始碼分析

作為傳遞訊息的神器,我一直對它十分感興趣,所以現在來看看它。

一般情況下,我們會在需要傳遞訊息的地方註冊一個物件:例如在Activity中

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

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

所以我們就從這個看起吧: 首先會呼叫EventBus.getDefault()得到EvenBus物件:


 static volatile EventBus defaultInstance;

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

可以看到,這裡採用的是double-check的單例模式。


private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
public EventBus() {
        this(DEFAULT_BUILDER);
    }

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

 EventBus(EventBusBuilder builder) {
        logger = builder.getLogger();
        //用來儲存訂閱方法引數型別和Subscription List
        subscriptionsByEventType = new HashMap<>();
        //用來儲存訂閱者和被訂閱方法的引數型別
        typesBySubscriber = new HashMap<>();
        //粘性事件
        stickyEvents = new ConcurrentHashMap<>();
        
        mainThreadSupport = builder.getMainThreadSupport();
        //主執行緒傳送器
        mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
        //後臺傳送器
        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;
    }


可以看到,在EventBus的構造方法中,主要建立了一個Map物件和三個不同型別的執行緒型別傳送器,可以匹配註解中的threadMode欄位。

先看一個用法:

 @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent1(String text){

        Log.d(TAG, "onMessageEvent1: "+text+"-----"+Thread.currentThread().getName());

    }

    @Subscribe(threadMode = ThreadMode.BACKGROUND)
    public void onMessageEvent2(String text){

        Log.d(TAG, "onMessageEvent2: "+text+"-----"+Thread.currentThread().getName());

    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessageEvent3(String text){

        Log.d(TAG, "onMessageEvent3: "+text+"-----"+Thread.currentThread().getName());

    }

    @Subscribe(threadMode = ThreadMode.ASYNC)
    public void onMessageEvent4(String text){
        Log.d(TAG, "onMessageEvent4: "+text+"-----"+Thread.currentThread().getName());

    }

    @Subscribe(threadMode = ThreadMode.MAIN_ORDERED)
    public void onMessageEvent5(String text){

        Log.d(TAG, "onMessageEvent5: "+text+"-----"+Thread.currentThread().getName());

    }


 new Thread(new Runnable() {
            @Override
            public void run() {
                String s = "aaaaaaaaaaaaaaaa";
                EventBus.getDefault().post(s);
            }
        }).start();

列印結束:

 onMessageEvent2: aaaaaaaaaaaaaaaa-----Thread-5
 onMessageEvent3: aaaaaaaaaaaaaaaa-----Thread-5
 onMessageEvent4: aaaaaaaaaaaaaaaa-----pool-1-thread-1
 onMessageEvent1: aaaaaaaaaaaaaaaa-----main
 onMessageEvent5: aaaaaaaaaaaaaaaa-----main

可以看到,五個方法都呼叫了,而且有些執行的執行緒不一樣。

我們先看看threadMode各個欄位的含義:

  • POSTING:預設的模式,開銷最小的模式。事件的處理在事件的傳送的那個執行緒。對應上面的事件3,也就是處理的事件的執行緒是我們傳送事件所在的執行緒。
  • MAIN:事件的處理在UI執行緒中執行。
  • BACKGROUND:事件的處理會在一個後臺執行緒中執行。如果傳送事件的執行緒不是UI執行緒,就直接用該傳送事件的執行緒。如果傳送事件的執行緒是UI執行緒,就會使用一個單獨的後臺執行緒,將按順序分發所有的事件。對於上面的事件2.
  • ASYNC:事件處理會在單獨的執行緒中執行,它一直與傳送事件的執行緒和主執行緒獨立,主要用於在後臺執行緒中執行耗時操作,每一個事件都會開啟一個執行緒(通過執行緒池)。應該限制執行緒數目。
  • MAIN_ORDERED:事件的處理在主執行緒,與MAIN不同在於,用這個模式,事件等排序等待分發。這個保證了傳送發不會阻塞。

然後我們看看EventBus的註冊事件:

public void register(Object subscriber) {
		//得到訂閱者的Class
        Class<?> subscriberClass = subscriber.getClass();
        //找到該CLass下的所有訂閱方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
            //對訂閱方法註冊
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

我們先看是怎麼找到訂閱方法的:

 private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
		//嘗試從快取中獲取該訂閱者的訂閱方法
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
		//如果沒有找到,就從下面連在方法中獲取。
        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 {
        //將獲取到的訂閱方法放置到快取中。
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

可以看到先從METHOD_CACHE 從找該類對應的所有訂閱方法,METHOD_CACHEConcurrentHashMap的例項,它是HashMap的一個執行緒安全,支援高效併發的版本。在預設理想情況下,ConcurrentHashMap可以支援16個執行緒執行併發寫操作及任意數量執行緒的讀操作。

首先從快取中獲得該訂閱者的所有訂閱方法,如果沒有獲取到,就有兩種方法去獲取,如果ignoreGeneratedIndex為true,表示忽略註解器生成的MyEventBusIndex,然後就使用反射來查詢;一般情況下該值預設為false,我們就會進入下面的方法:

 private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
 		//通過FindState物件來儲存找到的方法資訊
 		//從池中或建立使用
        FindState findState = prepareFindState();
        //初始化
        findState.initForSubscriber(subscriberClass);
        //從當前類開始遍歷該類的所有父類
        while (findState.clazz != null) {
        	//獲得SubscriberInfo
            findState.subscriberInfo = getSubscriberInfo(findState);
            if (findState.subscriberInfo != null) {
            //如果使用了MyEventBusIndex,將會到這裡並獲取訂閱方法資訊。
                SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                for (SubscriberMethod subscriberMethod : array) {
                    if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                        findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
            // 未使用MyEventBusIndex將會進入這裡使用反射獲取方法資訊
                findUsingReflectionInSingleClass(findState);
            }
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

這裡從池取出或建立FindState物件,並且呼叫getSubscriberInfo查詢是否有新新增的SubscriberInfoIndex,這個是需要新增編輯器支援的,並且在編譯器自動 生成,需要手動新增,這裡預設的情況下是不存在,所以會進入findUsingReflectionInSingleClass方法,通過反射來呼叫。,接著呼叫moveToSuperclass方法獲取其父類。最後將findState回收。

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();
            // 如果方法的修飾符是public
            //並且不是 Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            //獲取引數型別陣列
                Class<?>[] parameterTypes = method.getParameterTypes();
                //如果引數是1個
                //說明我們在用EventBus的時候,訂閱方法的引數只能有一個
                if (parameterTypes.length == 1) {
                //判斷該方法是否被Subscribe 註解修飾
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                    //如果被Subscribe 註解修飾,則進入這裡。
                        Class<?> eventType = parameterTypes[0];
                        //檢查是否已經添加了該eventType,eventType是由引數定義的
                        //如果返回false,說明父類也有這個方法,但是子類重寫了它。
                        if (findState.checkAdd(method, eventType)) {
                        //得到threadMode
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            //新增訂閱方法
                            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");
            }
        }
    }

在這裡,通過反射來獲取主要分為:

  1. 獲取類的方法
  2. 遍歷類,並且檢查
    1. 檢查方法修飾符是不是public
    2. 檢查引數數量是不是等於1
    3. 檢查方法是否含有SubScribe註解 如果上面的三個條件都滿足,就需要檢查方法和引數型別是否已經存在,是否此方法需要新增threadMode
  3. 根據檢查結果來判斷是否要新增threadMode

下面是checkAdd方法:


 final Map<Class, Object> anyMethodByEventType = new HashMap<>();

 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) {
            //map中沒有改引數和method
                return true;
            } else {
                if (existing instanceof Method) {
                //如果有該eventType的value,就比較在map裡面的value是不是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);
            }
        }




 private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
            methodKeyBuilder.setLength(0);
            methodKeyBuilder.append(method.getName());
            methodKeyBuilder.append('>').append(eventType.getName());

            String methodKey = methodKeyBuilder.toString();
            //得到方法所在的類
            Class<?> methodClass = method.getDeclaringClass();
            //檢查是否以前有存在
            Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
            if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
                // Only add if not already found in a sub class
                //如果不存在或者methodClass是methodClassOld的子類
                //就返回true,表示重新替換成子類的方法
                return true;
            } else {
                // Revert the put, old class is further down the class hierarchy
                //如果不是子類,就回退剛才的put
                subscriberClassByMethodKey.put(methodKey, methodClassOld);
                return false;
            }
        }

addCheck方法中,會先判斷anyMethodByEventType存不存key為eventType的一項,如果不存在,就返回true,並且將method新增到了anyMethodByEventType。如果存在,就看現在方法所在的class是不是之前方法所在class的子類,如果是子類,就替換之前存在的value,否則就還原之前的。

現在需要訂閱的方法找到了, 然後對每個訂閱的方法呼叫subscribe方法:

 // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    //引數型別
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //是否存在有該eventType的subscriptions 
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
	·		//subscriptionsByEventType裡面存放的是引數型別相同的所有方法
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            if (subscriptions.contains(newSubscription)) {
            //檢查是否已經被註冊了
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }

        int size = subscriptions.size();