EventBus學(xué)習(xí)

EventBus基本使用

發(fā)送事件:
EventBus.getDefault().post(new EmptyEvent());

訂閱事件:
EventBus.getDefault().register(this);
處理事件:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onRefresh(EmptyEvent event) {
    //TODO 接收到通知后需要進(jìn)行的操作
}
取消訂閱:
EventBus.getDefault().unregister(this);

EventBus的操作很簡(jiǎn)單,引入也很方便,那么它內(nèi)部是怎么實(shí)現(xiàn)的呢?事件的接收方是怎么收到事件的,會(huì)不會(huì)有遺漏或錯(cuò)亂?它的線程是怎么處理的?好,接下來(lái)一步一步看源碼~

class EventBus {

    //map中的key為Event類,value為訂閱該Event的Subscription(Object subscriber, SubscriberMethod subscriberMethod)列表
    //Subscription 類只有兩個(gè)成員變量,訂閱類 和 該類下的某個(gè)訂閱方法
    //核心參數(shù),post一個(gè)事件的時(shí)候能快速獲取到接收該事件的方法并調(diào)用
    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    //map中key為訂閱類,value為訂閱類訂閱的Event列表
    //該參數(shù)主要用于判斷一個(gè)類是否已經(jīng)register
    private final Map<Object, List<Class<?>>> typesBySubscriber;


    /**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * <p/>
     * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    // Must be called in synchronized block
    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);
            }
        }
    }


    /** Unregisters the given subscriber from all event classes. */
    public synchronized void unregister(Object subscriber) {
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                unsubscribeByEventType(subscriber, eventType);
            }
            typesBySubscriber.remove(subscriber);
        } else {
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

    private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
        List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions != null) {
            int size = subscriptions.size();
            for (int i = 0; i < size; i++) {
                Subscription subscription = subscriptions.get(i);
                if (subscription.subscriber == subscriber) {
                    subscription.active = false;
                    subscriptions.remove(i);
                    i--;
                    size--;
                }
            }
        }
    }

    public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        eventQueue.add(event);

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

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

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

    void invokeSubscriber(Subscription subscription, Object event) {
        try {
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }
}

總結(jié):

  1. A類訂閱事件 EventBus.getDefault().register(this); 做的事情:
    1> 獲取訂閱類A下的所有SubscriberMethod(含@Subscribe注解的,public的,非static的,非abstract的,只有一個(gè)參數(shù)的方法),得到 List<SubscriberMethod> methods;在此過程中,會(huì)遍歷父類(跳過系統(tǒng)類),添加父類的不同的(方法名,事件類型不完全相同)SubscriberMethod到methods
    2> 加鎖synchronized,接下來(lái)的操作都在鎖內(nèi)進(jìn)行
    3> 遍歷訂閱類A下的所有SubscriberMethod,每個(gè)SubscriberMethod都進(jìn)行如下操作
    4> 根據(jù)優(yōu)先級(jí),在 subscriptionsByEventType 中為該Event加入new Subscription(subscriber, subscriberMethod)
    5> 在typesBySubscriber 中為該訂閱類加入新的EventType
    6> subscriberMethod.sticky相關(guān)操作,待閱讀

  2. A類取消訂閱事件 EventBus.getDefault().unregister(this); 做的事情:
    1> typesBySubscriber 獲取訂閱類A訂閱的所有EventType
    2> 針對(duì)每個(gè)EventType,將subscriptionsByEventType 移除EventType下的所有Subscription.subscriber 為該類的Subscription
    3> typesBySubscriber 移除該類

  3. B類發(fā)送一個(gè)事件 EventBus.getDefault().post(new EmptyEvent()); 做的事情:
    0> eventInheritance為true的時(shí)候(默認(rèn)為true),獲取到該Event的父類Event/繼承的接口類Event列表,遍歷該列表,執(zhí)行以下操作
    1> 從subscriptionsByEventType 獲取到接收該Event的Subscription
    2> 遍歷Subscription列表,依次調(diào)用Subscription.subscriberMethod
    3> 這個(gè)過程中,確認(rèn)subscriberMethod的執(zhí)行線程,通過AsyncPoster,BackgroundPoster,HandlerPoster處理線程切換問題

class AsyncPoster implements Runnable, Poster {

    private final PendingPostQueue queue;
    private final EventBus eventBus;

    AsyncPoster(EventBus eventBus) {
        this.eventBus = eventBus;
        queue = new PendingPostQueue();
    }

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        eventBus.getExecutorService().execute(this);
    }

    @Override
    public void run() {
        PendingPost pendingPost = queue.poll();
        if(pendingPost == null) {
            throw new IllegalStateException("No pending post available");
        }
        eventBus.invokeSubscriber(pendingPost);
    }

}
final class BackgroundPoster implements Runnable, Poster {

    private final PendingPostQueue queue;
    private final EventBus eventBus;

    private volatile boolean executorRunning;

    BackgroundPoster(EventBus eventBus) {
        this.eventBus = eventBus;
        queue = new PendingPostQueue();
    }

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        //區(qū)別于SyncPoster的地方
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!executorRunning) {
                executorRunning = true;
                eventBus.getExecutorService().execute(this);
            }
        }
    }

    @Override
    public void run() {
        try {
            try {
                while (true) {
                    PendingPost pendingPost = queue.poll(1000);
                    if (pendingPost == null) {
                        synchronized (this) {
                            // Check again, this time in synchronized
                            pendingPost = queue.poll();
                            if (pendingPost == null) {
                                executorRunning = false;
                                return;
                            }
                        }
                    }
                    eventBus.invokeSubscriber(pendingPost);
                }
            } catch (InterruptedException e) {
                eventBus.getLogger().log(Level.WARNING, Thread.currentThread().getName() + " was interruppted", e);
            }
        } finally {
            executorRunning = false;
        }
    }

}
public class HandlerPoster extends Handler implements Poster {

    private final PendingPostQueue queue;
    private final int maxMillisInsideHandleMessage;
    private final EventBus eventBus;
    private boolean handlerActive;

    protected HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
        super(looper);
        this.eventBus = eventBus;
        this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
        queue = new PendingPostQueue();
    }

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!handlerActive) {
                handlerActive = true;
                if (!sendMessage(obtainMessage())) {
                    throw new EventBusException("Could not send handler message");
                }
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }
}

EventBus提供的幾種線程模式:

/**
 * Each subscriber method has a thread mode, which determines in which thread the method is to be called by EventBus.
 * EventBus takes care of threading independently from the posting thread.
 * 
 * @see EventBus#register(Object)
 * @author Markus
 */
public enum ThreadMode {
    /**
     * Subscriber will be called directly in the same thread, which is posting the event. This is the default. Event delivery
     * implies the least overhead because it avoids thread switching completely. Thus this is the recommended mode for
     * simple tasks that are known to complete in a very short time without requiring the main thread. Event handlers
     * using this mode must return quickly to avoid blocking the posting thread, which may be the main thread.
     */
    /**
     * 訂閱服務(wù)器將直接在發(fā)布事件的同一線程中調(diào)用。這是默認(rèn)設(shè)置。
     * 事件傳遞意味著開銷最小,因?yàn)樗耆苊饬司€程切換。
     * 因此,對(duì)于已知在非常短的時(shí)間內(nèi)完成而不需要主線程的簡(jiǎn)單任務(wù),建議使用這種模式。
     * 使用此模式的事件處理程序必須快速返回,以避免阻塞可能是主線程的發(fā)布線程。
     */
    POSTING,

    /**
     * On Android, subscriber will be called in Android's main thread (UI thread). If the posting thread is
     * the main thread, subscriber methods will be called directly, blocking the posting thread. Otherwise(否則,另外) the event
     * is queued for delivery (non-blocking). Subscribers using this mode must return quickly to avoid blocking the main thread.
     * If not on Android, behaves the same as {@link #POSTING}.
     */
    MAIN,

    /**
     * On Android, subscriber will be called in Android's main thread (UI thread). Different from {@link #MAIN},
     * the event will always be queued for delivery. This ensures that the post call is non-blocking.
     */
    MAIN_ORDERED,

    /**
     * On Android, subscriber will be called in a background thread. If posting thread is not the main thread, subscriber methods
     * will be called directly in the posting thread. If the posting thread is the main thread, EventBus uses a single
     * background thread, that will deliver all its events sequentially. Subscribers using this mode should try to
     * return quickly to avoid blocking the background thread. If not on Android, always uses a background thread.
     */
    BACKGROUND,

    /**
     * Subscriber will be called in a separate thread. This is always independent from the posting thread and the
     * main thread. Posting events never wait for subscriber methods using this mode. Subscriber methods should
     * use this mode if their execution might take some time, e.g. for network access. Avoid triggering a large number
     * of long running asynchronous subscriber methods at the same time to limit the number of concurrent threads. EventBus
     * uses a thread pool to efficiently reuse threads from completed asynchronous subscriber notifications.
     */
    ASYNC
}

POSTING:默認(rèn)線程,和發(fā)布事件的線程一致;
MAIN:主線程,如果發(fā)布事件的線程是主線程,則直接調(diào)用訂閱者的方法,會(huì)阻塞發(fā)布線程,否則事件排隊(duì)等待傳遞,非阻塞;
MAIN_ORDERED:主線程,事件始終排隊(duì)等待傳遞,確保發(fā)布事件的調(diào)用是非阻塞的;
BACKGROUND:子線程,如果發(fā)布事件的線程不是主線程,則和發(fā)布事件的線程一致,否則使用單個(gè)后臺(tái)線程,按順序傳遞所有事件,共用一個(gè)子線程;
ASYNC:子線程,一個(gè)單獨(dú)的線程,區(qū)別于發(fā)布事件的線程以及主線程,每次都從線程池中execute一個(gè)新的線程,不共用。

使用EventBus需要注意的地方:

  1. 一個(gè)類注冊(cè)監(jiān)聽的時(shí)候,必須有含@Subscribe注解的公有方法
  2. 一個(gè)類只能注冊(cè)一次監(jiān)聽,否則subscriptionsByEventType添加Subscription的時(shí)候會(huì)拋出異常
    new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event " + eventType)
  3. 父類和子類有相同的訂閱方法(方法名,事件類型相同,線程無(wú)所謂)的時(shí)候,編譯通過,只會(huì)執(zhí)行子類的訂閱方法,因?yàn)閞egister的時(shí)候會(huì)遍歷父類,添加父類的不同的(方法名,事件類型不完全相同)SubscriberMethod,相同的則不添加
  4. 默認(rèn)情況下,發(fā)送一個(gè)子類Event的時(shí)候,接收子類Event和父類Event的方法都會(huì)調(diào)用,如果不想接收父類Event的方法被調(diào)用,設(shè)置eventInheritance為false即可;發(fā)送父類Event,只有接收父類Event的方法被調(diào)用
  5. 一定要記得unregister,否則subscriptionsByEventType中一直含有該訂閱方法,發(fā)送事件的時(shí)候仍然會(huì)去調(diào)用,造成異常
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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