關於EventBus的onEvent()、onEventMainThread()、onEventBackgroundThread()、onEventAsync()的解釋

幾句話概括:

1. onEvent()

   使用onEvent來接收事件,那麼接收事件和post事件在同一個線程中執行

2. onEventMainThread()

   使用onEventMainThread來接收事件,那麼不論post事件在哪個線程運行,接收事件永遠在UI線程執行

3. onEventBackgroundThread()

   使用onEventBackgroundThread來接收事件,如果post事件在子線程運行,那麼接收事件直接在同一個線程
   運行,如果post事件在UI線程,那麼會啓動一個子線程接收事件

4. onEventAsync()

使用onEventAsync接收事件,無論post事件在哪個線程 (UI或者子線程) 執行,接收事件都會在一個新的子線程執行

 

具體可參考源碼:

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
        //線程切換之前進行攔截
        if (!needInvokeSubscriber(subscription, event)) {
            return;
        }
        switch (subscription.subscriberMethod.threadMode) {
            case POSTING:
                invokeSubscriber(subscription, event);
                break;
            case MAIN:
                if (isMainThread) {
                    invokeSubscriber(subscription, event);
                } else {
                    mainThreadPoster.enqueue(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);
        }
    }

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