EventBus 3.1.1 源碼解析

* 本篇文章已授權(quán)微信公眾號 guolin_blog(郭霖)獨家發(fā)布

一、本文需要解決的問題

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

  1. 這個框架涉及到一種設(shè)計模式叫做觀察者模式,什么是觀察者模式?
  2. 事件如何進行定義,有沒有相關(guān)限制?
  3. 觀察者綁定觀察事件的時候,綁定方法的命名有限制嗎?
  4. 事件發(fā)送和接收的原理?

二、初步使用

為了研究源碼的方便,我寫了一個簡單的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

三、源碼分析

關(guān)于觀察者模式
  • 簡介:觀察者模式是設(shè)計模式中的一種。它是為了定義對象間的一種一對多的依賴關(guān)系,即當(dāng)一個對象的狀態(tài)發(fā)生改變時,所有依賴于它的對象都得到通知并被自動更新。
  • 如何使用:這里傳送門有相關(guān)的demo,這里不再詳述。
  • 重點:在這個模式中主要包含兩個重要的角色:發(fā)布者訂閱者(又稱觀察者)。對應(yīng)EventBus來說,發(fā)布者即發(fā)送消息的一方(即調(diào)用EventBus.getDefault().post(event)的一方),訂閱者即接收消息的一方(即調(diào)用EventBus.getDefault().register()的一方)。
    我們已經(jīng)解決了第一個問題~
關(guān)于事件

這里指的事件其實是一個泛泛的統(tǒng)稱,指的是一個概念上的東西(當(dāng)時我還以為一定要以啥Event命名...),通過查閱官方文檔,我知道事件的命名格式并沒有任何要求,你可以定義一個對象作為事件,也可以發(fā)送基本數(shù)據(jù)類型如int,String等作為一個事件。后續(xù)的源碼分析我也會再次證明一下。

具體分析

從函數(shù)入口開始分析:
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;
    }
}

分析:

  • 如果緩存中有對應(yīng)class的訂閱方法列表,則直接返回,這里我們是第一次創(chuàng)建,所以此時subscriberMethods為空;
  • 接下來會有一個參數(shù)判斷,通過查看前面的創(chuàng)建過程,ignoreGeneratedIndex默認(rèn)為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();
}

這個方法是創(chuàng)建一個新的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的內(nèi)部類,這個方法主要做一個初始化的工作。

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,后續(xù)我們可以再回到這里看看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作為注解的方法進行處理(?。?!部分的代碼),先經(jīng)過一輪檢查,看看findState.subscriberMethods是否存在,如果沒有的話,將方法名,threadMode,優(yōu)先級,是否為sticky方法封裝為SubscriberMethod對象,添加到subscriberMethods列表中。

什么是sticky event?

sticky event,中文名為粘性事件。普通事件是先注冊,然后發(fā)送事件才能收到;而粘性事件,在發(fā)送事件之后再訂閱該事件也能收到。此外,粘性事件會保存在內(nèi)存中,每次進入都會去內(nèi)存中查找獲取最新的粘性事件,除非你手動解除注冊。

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

之后這個while循環(huán)會繼續(xù)檢查父類,當(dāng)然遇到系統(tǒng)相關(guān)的類時會自動跳過,以提升性能。

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做相應(yīng)處理,存儲在FindState池中,方便下一次使用,提高性能。

  1. EventBus#subscribe():
    返回subscriberMethods之后,register方法的最后會調(diào)用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);
        }
    }
}

分析:

  • 首先,根據(jù)subscriberMethod.eventType(在Demo里面指的是TestEvent),在subscriptionsByEventType去查找一個CopyOnWriteArrayList<Subscription> ,如果沒有則創(chuàng)建一個新的CopyOnWriteArrayList;
  • 然后將這個CopyOnWriteArrayList放入subscriptionsByEventType中,這里的subscriptionsByEventType是一個Map,key為eventType,value為CopyOnWriteArrayList<Subscription>,這個Map非常重要,后續(xù)還會用到它;
  • 接下來,就是添加newSubscription,它屬于Subscription類,里面包含著subscriber和subscriberMethod等信息,同時這里有一個優(yōu)先級的判斷,說明它是按照優(yōu)先級添加的。優(yōu)先級越高,會插到在當(dāng)前List靠前面的位置;
  • typesBySubscriber這個類也是一個Map,key為subscriber,value為subscribedEvents,即所有的eventType列表,這個類我找了一下,發(fā)現(xiàn)在EventBus#isRegister()方法中有用到,應(yīng)該是用來判斷這個Subscriber是否已被注冊過。然后將當(dāng)前的eventType添加到subscribedEvents中;
  • 最后,判斷是否是sticky。如果是sticky事件的話,到最后會調(diào)用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事件相當(dāng)于把事件發(fā)送出去,我們看看訂閱者是如何接收到事件的。

  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和其他一些標(biāo)志位;
  • 然后把傳入的event,保存到了當(dāng)前線程中的一個變量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 代碼段分析

  • 這里涉及到兩個標(biāo)志位,第一個是isMainThread,判斷是否為UI線程;第二個是isPosting,作用是防止方法多次調(diào)用。
  • 最后調(diào)用到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類型,然后有一個標(biāo)志位eventInheritance判斷,默認(rèn)為true,作用在相關(guān)代碼注釋有說,如果設(shè)為true的話,它會拿到Event父類的class類型,設(shè)為false,可以在一定程度上提高性能;
  • 接下來是lookupAllEventTypes()方法,就是取出Event及其父類和接口的class列表,當(dāng)然重復(fù)取的話會影響性能,所以它也有做一個eventTypesCache的緩存,這樣不用都重復(fù)調(diào)用getClass()方法。
  • 然后是postSingleEventForEventType()方法,這里就很清晰了,就是直接根據(jù)Event類型從subscriptionsByEventType中取出對應(yīng)的subscriptions,與之前的代碼對應(yīng),最后調(diào)用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);
    }
}

這里會根據(jù)threadMode來判斷應(yīng)該在哪個線程中去執(zhí)行方法:

  • POSTING:執(zhí)行invokeSubscriber()方法,就是直接反射調(diào)用;
  • MAIN:首先去判斷當(dāng)前是否在UI線程,如果是的話則直接反射調(diào)用,否則調(diào)用mainThreadPoster#enqueue(),即把當(dāng)前的方法加入到隊列之中,然后通過handler去發(fā)送一個消息,在handler的handleMessage中去執(zhí)行方法。具體邏輯在HandlerPoster.java中;
  • MAIN_ORDERED:與上面邏輯類似,順序執(zhí)行我們的方法;
  • BACKGROUND:判斷當(dāng)前是否在UI線程,如果不是的話直接反射調(diào)用,是的話通過backgroundPoster.enqueue()將方法加入到后臺的一個隊列,最后通過線程池去執(zhí)行;
  • ASYNC:與BACKGROUND的邏輯類似,將任務(wù)加入到后臺的一個隊列,最終由Eventbus中的一個線程池去調(diào)用,這里的線程池與BACKGROUND邏輯中的線程池用的是同一個。

補充:BACKGROUND和ASYNC有什么區(qū)別呢?
BACKGROUND中的任務(wù)是一個接著一個的去調(diào)用,而ASYNC則會即時異步運行,具體的可以對比AsyncPoster.java和BackgroundPoster.java兩者代碼實現(xiàn)的區(qū)別。

到這里,我們就解決了第四個問題,事件的發(fā)送和接收,主要是通過subscriptionsByEventType這個非常重要的列表,我們將訂閱即接收事件的方法存儲在這個列表,發(fā)布事件的時候在列表中查詢出相對應(yīng)的方法并執(zhí)行~

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

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容