Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

EventBus 源碼剖析:從註冊到事件分發的完整鏈路

編輯:關於 Android 程式設計

上一篇我們走過了 EventBus 的基本用法,這次深入源碼,看看「事件總線」四個字背後到底做了什麼。開始之前先補一塊前置知識。

一、Java 反射機制速覽

定義:反射是指在運行時,對於任意一個類都能獲知其所有屬性與方法,對於任意一個對象都能調用其任意方法與屬性。這種動態獲取信息、動態調用對象方法的能力,就是反射機制。

核心類: java.lang.Class、java.lang.reflect.Constructor、Field、Method、Modifier。

常用方法:

  • getDeclaredMethods():獲取所有已聲明的方法
  • getDeclaredMethod(名稱, 參數類型...):獲取指定方法
  • getFields():返回所有公有屬性
  • getDeclaredField(名稱):獲取指定屬性

標準三步:拿到目標類的 Class 對象 → 拿到要調用的 Method → 調用 invoke()。

Class cls = Class.forName("chb.test.reflect.Student");
Method m = cls.getDeclaredMethod("toString", int.class, String.class);
m.invoke(cls.newInstance(), 20, "chb");

二、四種訂閱函數

EventBus 的觀察者方法共有四種,都以 onEvent 開頭,差別在於運行線程:

  • onEvent:事件在哪個線程發布,就在哪個線程回調。因此不能在裡面做耗時操作,否則會拖延整個事件分發流程。
  • onEventMainThread:無論事件從哪發布,都在 UI 線程回調。這在 Android 中極其實用,因為更新界面只能在主線程;同樣不適合耗時任務。
  • onEventBackground:事件若在主線程發布,回調跑在子線程;事件本來就在子線程發布,則直接在該子線程執行。
  • onEventAsync:無論事件從哪發布,都新建一個子線程來執行回調。

兩個基礎概念:EventBus.post() 負責發布事件;上述四種方法負責接收事件。

三、源碼解析

3.1 入口:getDefault().register(this)

static volatile EventBus defaultInstance;

public static EventBus getDefault() {
    if (defaultInstance == null) {
        synchronized (EventBus.class) {
            if (defaultInstance == null) {
                defaultInstance = new EventBus();
            }
        }
    }
    return defaultInstance;
}

典型的雙重校驗鎖單例。用 volatile 修飾是為了防止指令重排序導致的對象未完全初始化就被使用。

3.2 register:找到所有訂閱方法

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

findSubscriberMethods() 先查緩存——METHOD_CACHE 是一個以訂閱類為 key、方法列表為 value 的 ConcurrentHashMap。首次進入必然未命中,於是走反射路徑:

if (ignoreGeneratedIndex) {
    subscriberMethods = findUsingReflection(subscriberClass);
} else {
    subscriberMethods = findUsingInfo(subscriberClass);
}

反射實現的核心在 findUsingReflectionInSingleClass():

methods = findState.clazz.getDeclaredMethods();
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)) {
            throw new EventBusException("@Subscribe method must have "
                    + "exactly 1 parameter");
        }
    }
}

這裡有幾個值得注意的細節:用 getDeclaredMethods() 而非 getMethods(),是因為前者在 Activity 這類「胖子類」上明顯更快;回退邏輯會捕獲 NoClassDefFoundError 並降級到 getMethods();嚴格模式下會校驗方法必須 public、非靜態、非抽象,且只有一個參數。

3.3 subscribe:建立事件到方法的映射

private void subscribe(Object subscriber,
                       SubscriberMethod subscriberMethod,
                       boolean sticky, int priority) {
    Class<?> eventType = subscriberMethod.eventType;
    CopyOnWriteArrayList<Subscription> subscriptions =
            subscriptionsByEventType.get(eventType);
    Subscription newSubscription =
            new Subscription(subscriber, subscriberMethod, priority);

    if (subscriptions == null) {
        subscriptions = new CopyOnWriteArrayList<>();
        subscriptionsByEventType.put(eventType, subscriptions);
    } else {
        for (Subscription subscription : subscriptions) {
            if (subscription.equals(newSubscription)) {
                throw new EventBusException("Subscriber already registered");
            }
        }
    }

    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<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    if (sticky) {
        Object stickyEvent;
        synchronized (stickyEvents) {
            stickyEvent = stickyEvents.get(eventType);
        }
        if (stickyEvent != null) {
            postToSubscription(newSubscription, stickyEvent,
                    Looper.getMainLooper() == Looper.myLooper());
        }
    }
}

這段代碼維護了兩個雙向索引:subscriptionsByEventType(事件類型 → 訂閱列表,按 priority 插入)與 typesBySubscriber(訂閱者 → 事件類型列表)。有了這兩個映射,無論從事件找方法還是從訂閱者找事件,都是 O(1) 定位。用 CopyOnWriteArrayList 是因為註冊與分發往往發生在不同線程,寫時複製能避免加鎖。

register 三步總結:

  1. 找出被註冊者中所有標了 @Subscribe 的方法;
  2. 遍歷这些方法,為每個事件類型創建 Subscription 並插入對應列表;
  3. 把事件類型記錄到該訂閱者的事件列表中。

3.4 post:事件分發

post(Object event) 本身邏輯很薄,主要負責維護 PostingThreadState,真正的判斷交給 postSingleEvent():

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) {
        if (eventClass != NoSubscriberEvent.class
                && eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

值得注意的是 findEventTypes() 會把父類與接口對應的事件類型一併納入,這解釋了為什麼訂閱父類型也能收到子類事件。另外若無任何訂閱者,會補發一個 NoSubscriberEvent,方便統一監測「事件沒人接」的問題。

3.5 postToSubscription:線程切換的關鍵

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

這裡的 threadMode 正是註冊階段從 @Subscribe 註解中讀出的值,串起了整個鏈路。四種模式的分派邏輯:

  • PostThread:直接反射調用,線程不變。
  • MainThread:已在主線程則直接調用,否則通過 mainThreadPoster 入隊,由內部 Handler 發消息到主線程執行。
  • BackgroundThread:在子線程則直接調用;在主線程則入隊,交給 Executors.newCachedThreadPool() 這個線程池執行。
  • Async:無論何時都入隊,交給同一個線程池。

BackgroundThread 與 Async 的區別在於並發策略:BackgroundThread 的任務串行執行,用一個布爾變量 handlerActive 控制同一時間只有一個任務在跑;Async 則允許動態並發。

四、小結

把源碼看透之後,EventBus 並不神秘:register 通過反射掃描出當前對象中所有匹配的方法,把它們按事件類型存進幾個 Map;post 則依據事件實參的類型去 Map 裡查出訂閱列表,再按線程策略反射調用。

拋開「發布者、訂閱者、事件、總線」這套術語,本質就是:一個單例內部維護著若干 Map,存了一批方法引用;post 不過是按參數查表並反射執行。理解到這一層,你就能自己判斷它在什麼場景下合適、什麼場景下反而會成為維護負擔。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved