EventBus 3.1.1 原始碼解析

張朝旭發表於2019-02-19
* 本篇文章已授權微信公眾號 guolin_blog(郭霖)獨家釋出

一、本文需要解決的問題

我研究EventBus原始碼的目的是解決以下幾個我在使用過程中所思考的問題:

  1. 這個框架涉及到一種設計模式叫做觀察者模式,什麼是觀察者模式?
  2. 事件如何進行定義,有沒有相關限制?
  3. 觀察者繫結觀察事件的時候,繫結方法的命名有限制嗎?
  4. 事件傳送和接收的原理?

二、初步使用

為了研究原始碼的方便,我寫了一個簡單的demo。

定義事件

TestEvent.java:

public class TestEvent {
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }
}
複製程式碼
主Activity

MainActivity.java:

public class MainActivity extends AppCompatActivity {

    private Button button;
    private TextView textView;

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

        button = findViewById(R.id.button);
        textView = findViewById(R.id.text);

        EventBus.getDefault().register(this);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                TestEvent event = new TestEvent();
                event.setMsg("已接收到事件!");
                EventBus.getDefault().post(event);
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTestEvent(TestEvent event) {
        textView.setText(event.getMsg());
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
複製程式碼
執行效果

demo.gif

三、原始碼分析

關於觀察者模式
  • 簡介:觀察者模式是設計模式中的一種。它是為了定義物件間的一種一對多的依賴關係,即當一個物件的狀態發生改變時,所有依賴於它的物件都得到通知並被自動更新。
  • 如何使用:這裡傳送門有相關的demo,這裡不再詳述。
  • 重點:在這個模式中主要包含兩個重要的角色:釋出者訂閱者(又稱觀察者)。對應EventBus來說,釋出者即傳送訊息的一方(即呼叫EventBus.getDefault().post(event)的一方),訂閱者即接收訊息的一方(即呼叫EventBus.getDefault().register()的一方)。 我們已經解決了第一個問題~
關於事件

這裡指的事件其實是一個泛泛的統稱,指的是一個概念上的東西(當時我還以為一定要以啥Event命名...),通過查閱官方文件,我知道事件的命名格式並沒有任何要求,你可以定義一個物件作為事件,也可以傳送基本資料型別如int,String等作為一個事件。後續的原始碼分析我也會再次證明一下。

具體分析

從函式入口開始分析: 1.EventBus#getDefault():

public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}
複製程式碼

這裡就是採用雙重校驗並加鎖的單例模式生成EventBus例項。

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}
複製程式碼

由於我們傳入的為this,即MainActivity的例項,所以第一行程式碼獲取了訂閱者的class物件,然後會找出所有訂閱的方法。我們看一下第二行的邏輯。 SubscriberMethodFinder#findSubscriberMethods():

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;
    }
}
複製程式碼

分析:

  • 如果快取中有對應class的訂閱方法列表,則直接返回,這裡我們是第一次建立,所以此時subscriberMethods為空;
  • 接下來會有一個引數判斷,通過檢視前面的建立過程,ignoreGeneratedIndex預設為false,進入else程式碼塊,後面生成subscriberMethods成功的話會加入到快取中,失敗的話會throw異常。

2.SubscriberMethodFinder#findUsingInfo():

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
    // 2.1
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    // 2.2
    while (findState.clazz != 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 {
            // 2.3
            findUsingReflectionInSingleClass(findState);
        }
        findState.moveToSuperclass();
    }
    // 2.4
    return getMethodsAndRelease(findState);
}
複製程式碼

2.1 SubscriberMethodFinder#prepareFindState():

private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];

private FindState prepareFindState() {
    synchronized(FIND_STATE_POOL) {
        for (int i = 0; i < POOL_SIZE; i++) {
            FindState state = FIND_STATE_POOL[i];
            if (state != null) {
                FIND_STATE_POOL[i] = null;
                return state;
            }
        }
    }
    return new FindState();
}
複製程式碼

這個方法是建立一個新的FindState類,通過兩種方法獲取,一種是從FIND_STATE_POOL即FindState池中取出可用的FindState,如果沒有的話,則通過第二種方式:直接new一個新的FindState物件。 FindState#initForSubscriber():

static class FindState {
    // 省略程式碼
    void initForSubscriber(Class<?> subscriberClass) {
        this.subscriberClass = clazz = subscriberClass;
        skipSuperClasses = false;
        subscriberInfo = null;
    }
   // 省略程式碼
}
複製程式碼

FindState類是SubscriberMethodFinder的內部類,這個方法主要做一個初始化的工作。

2.2 SubscriberMethodFinder#getSubscriberInfo():

private SubscriberInfo getSubscriberInfo(FindState findState) {
    if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
        SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
        if (findState.clazz == superclassInfo.getSubscriberClass()) {
            return superclassInfo;
        }
    }
    if (subscriberInfoIndexes != null) {
        for (SubscriberInfoIndex index: subscriberInfoIndexes) {
            SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
            if (info != null) {
                return info;
            }
        }
    }
    return null;
}
複製程式碼

這裡由於初始化的時候,findState.subscriberInfo和subscriberInfoIndexes為空,所以這裡直接返回null,後續我們可以再回到這裡看看subscriberInfo有什麼作用。

2.3 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;
    }
    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();
                        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");
        }
    }
}
複製程式碼

這個方法的邏輯是: 通過反射的方式獲取訂閱者類中的所有宣告方法,然後在這些方法裡面尋找以@Subscribe作為註解的方法進行處理(!!!部分的程式碼),先經過一輪檢查,看看findState.subscriberMethods是否存在,如果沒有的話,將方法名,threadMode,優先順序,是否為sticky方法封裝為SubscriberMethod物件,新增到subscriberMethods列表中。

什麼是sticky event?

sticky event,中文名為粘性事件。普通事件是先註冊,然後傳送事件才能收到;而粘性事件,在傳送事件之後再訂閱該事件也能收到。此外,粘性事件會儲存在記憶體中,每次進入都會去記憶體中查詢獲取最新的粘性事件,除非你手動解除註冊。

在這裡我們解決了第二個和第三個問題,方法的命名並沒有任何要求,只是加上@Subscribe註解即可!同時事件的命名也沒有任何要求!

之後這個while迴圈會繼續檢查父類,當然遇到系統相關的類時會自動跳過,以提升效能。

2.4 SubscriberMethodFinder#getMethodsAndRelease

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
    List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
    findState.recycle();
    synchronized(FIND_STATE_POOL) {
        for (int i = 0; i < POOL_SIZE; i++) {
            if (FIND_STATE_POOL[i] == null) {
                FIND_STATE_POOL[i] = findState;
                break;
            }
        }
    }
    return subscriberMethods;
}
複製程式碼

這裡將subscriberMethods列表直接返回,同時會把findState做相應處理,儲存在FindState池中,方便下一次使用,提高效能。

  1. EventBus#subscribe(): 返回subscriberMethods之後,register方法的最後會呼叫subscribe方法:
public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    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++) {
        if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }
    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);
    if (subscriberMethod.sticky) {
        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);
        }
    }
}
複製程式碼

分析:

  • 首先,根據subscriberMethod.eventType(在Demo裡面指的是TestEvent),在subscriptionsByEventType去查詢一個CopyOnWriteArrayList ,如果沒有則建立一個新的CopyOnWriteArrayList;
  • 然後將這個CopyOnWriteArrayList放入subscriptionsByEventType中,這裡的subscriptionsByEventType是一個Map,key為eventType,value為CopyOnWriteArrayList,這個Map非常重要,後續還會用到它;
  • 接下來,就是新增newSubscription,它屬於Subscription類,裡面包含著subscriber和subscriberMethod等資訊,同時這裡有一個優先順序的判斷,說明它是按照優先順序新增的。優先順序越高,會插到在當前List靠前面的位置;
  • typesBySubscriber這個類也是一個Map,key為subscriber,value為subscribedEvents,即所有的eventType列表,這個類我找了一下,發現在EventBus#isRegister()方法中有用到,應該是用來判斷這個Subscriber是否已被註冊過。然後將當前的eventType新增到subscribedEvents中;
  • 最後,判斷是否是sticky。如果是sticky事件的話,到最後會呼叫checkPostStickyEventToSubscription()方法。

這裡其實就是將所有含@Subscribe註解的訂閱方法最終儲存在subscriptionsByEventType中。

  1. EventBus#checkPostStickyEventToSubscription():
private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
    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, isMainThread());
    }
}
複製程式碼

接下來,我們重點看post()和postToSubscription()方法。post事件相當於把事件傳送出去,我們看看訂閱者是如何接收到事件的。

  1. EventBus#post():
/** Posts the given event to the event bus. */
public void post(Object event) {
    // 5.1
    PostingThreadState postingState = currentPostingThreadState.get();
    List <Object> eventQueue = postingState.eventQueue;
    eventQueue.add(event);

    // 5.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);
            }
        } finally {
            postingState.isPosting = false;
            postingState.isMainThread = false;
        }
    }
}
複製程式碼

5.1 程式碼段分析

  • currentPostingThreadState是一個ThreadLocal型別的,裡面儲存了PostingThreadState,而PostingThreadState中包含了一個eventQueue和其他一些標誌位;
  • 然後把傳入的event,儲存到了當前執行緒中的一個變數PostingThreadState的eventQueue中。
private final ThreadLocal <PostingThreadState> currentPostingThreadState = new ThreadLocal <PostingThreadState> () {
    @Override
    protected PostingThreadState initialValue() {
        return new PostingThreadState();
    }
};

/** For ThreadLocal, much faster to set (and get multiple values). */
final static class PostingThreadState {
    final List <Object> eventQueue = new ArrayList<>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}
複製程式碼

5.2 程式碼段分析

  • 這裡涉及到兩個標誌位,第一個是isMainThread,判斷是否為UI執行緒;第二個是isPosting,作用是防止方法多次呼叫。
  • 最後呼叫到postSingleEvent()方法
  1. EventBus#postSingleEvent():
private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {
        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 {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
    if (!subscriptionFound) {
        if (logNoSubscriberMessages) {
            logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
            eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class <?> eventClass) {
    CopyOnWriteArrayList <Subscription> subscriptions;
    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;
}
複製程式碼
  • 這裡會首先取出Event的class型別,然後有一個標誌位eventInheritance判斷,預設為true,作用在相關程式碼註釋有說,如果設為true的話,它會拿到Event父類的class型別,設為false,可以在一定程度上提高效能;
  • 接下來是lookupAllEventTypes()方法,就是取出Event及其父類和介面的class列表,當然重複取的話會影響效能,所以它也有做一個eventTypesCache的快取,這樣不用都重複呼叫getClass()方法。
  • 然後是postSingleEventForEventType()方法,這裡就很清晰了,就是直接根據Event型別從subscriptionsByEventType中取出對應的subscriptions,與之前的程式碼對應,最後呼叫postToSubscription()方法。
  1. EventBus#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:
            if (mainThreadPoster != null) {
                mainThreadPoster.enqueue(subscription, event);
            } else {
                // temporary: technically not correct as poster not decoupled from subscriber
                invokeSubscriber(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);
    }
}
複製程式碼

這裡會根據threadMode來判斷應該在哪個執行緒中去執行方法:

  • POSTING:執行invokeSubscriber()方法,就是直接反射呼叫;
  • MAIN:首先去判斷當前是否在UI執行緒,如果是的話則直接反射呼叫,否則呼叫mainThreadPoster#enqueue(),即把當前的方法加入到佇列之中,然後通過handler去傳送一個訊息,在handler的handleMessage中去執行方法。具體邏輯在HandlerPoster.java中;
  • MAIN_ORDERED:與上面邏輯類似,順序執行我們的方法;
  • BACKGROUND:判斷當前是否在UI執行緒,如果不是的話直接反射呼叫,是的話通過backgroundPoster.enqueue()將方法加入到後臺的一個佇列,最後通過執行緒池去執行;
  • ASYNC:與BACKGROUND的邏輯類似,將任務加入到後臺的一個佇列,最終由Eventbus中的一個執行緒池去呼叫,這裡的執行緒池與BACKGROUND邏輯中的執行緒池用的是同一個。

補充:BACKGROUND和ASYNC有什麼區別呢? BACKGROUND中的任務是一個接著一個的去呼叫,而ASYNC則會即時非同步執行,具體的可以對比AsyncPoster.java和BackgroundPoster.java兩者程式碼實現的區別。

到這裡,我們就解決了第四個問題,事件的傳送和接收,主要是通過subscriptionsByEventType這個非常重要的列表,我們將訂閱即接收事件的方法儲存在這個列表,釋出事件的時候在列表中查詢出相對應的方法並執行~

這篇文章會同步到我的個人日誌,如有問題,請大家踴躍提出,謝謝大家!

相關文章