当前位置: 首页 > 工具软件 > EventBus > 使用案例 >

EventBus源码解析(三)EventBus类

洪俊能
2023-12-01

EventBus类

public class EventBus {
    /** Log tag, apps may override it. */
    public static String TAG = "EventBus";

    //单实例EventBus,默认
    static volatile EventBus defaultInstance;

    private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

    //此事件类型 :此事件和它的父类,接口组成的集合
    private static final Map<Class<?>, List<Class<?>>> eventTypesCache = new HashMap<>();

    //此事件类型 :订阅这个事件的所有订阅者信息
    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;

    //订阅者 :它订阅的所有事件类型
    private final Map<Object, List<Class<?>>> typesBySubscriber;

    //sticky事件类型 :sticky事件
    private final Map<Class<?>, Object> stickyEvents;

    //在当前线程存储数据:PostingThreadState(发射线程状态)
    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

    // @Nullable
    private final MainThreadSupport mainThreadSupport;
    // 发射器
    private final Poster mainThreadPoster;  //若支持主线程则创建HandlerPoster
    private final BackgroundPoster backgroundPoster;
    private final AsyncPoster asyncPoster;
    //订阅方法查找
    private final SubscriberMethodFinder subscriberMethodFinder;
    //线程池
    private final ExecutorService executorService;

    private final boolean throwSubscriberException;
    private final boolean logSubscriberExceptions;
    private final boolean logNoSubscriberMessages;
    private final boolean sendSubscriberExceptionEvent;
    private final boolean sendNoSubscriberEvent;
    private final boolean eventInheritance;

    //注解数量
    private final int indexCount;
    private final Logger logger;

    /** 单实例 */
    public static EventBus getDefault() {
        EventBus instance = defaultInstance;
        if (instance == null) {
            synchronized (EventBus.class) {
                instance = EventBus.defaultInstance;
                if (instance == null) {
                    instance = EventBus.defaultInstance = new EventBus();
                }
            }
        }
        return instance;
    }

    public static EventBusBuilder builder() {
        return new EventBusBuilder();
    }

    /** 清除缓存*/
    public static void clearCaches() {
        SubscriberMethodFinder.clearCaches();   //清除订阅此事件的所有订阅方法
        eventTypesCache.clear();    //清除此订阅方法
    }

    /** 创建一个新的EventBus,调用EventBus(EventBusBuilder builder)*/
    public EventBus() {
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
        logger = builder.getLogger();
        subscriptionsByEventType = new HashMap<>();
        typesBySubscriber = new HashMap<>();
        stickyEvents = new ConcurrentHashMap<>();
        mainThreadSupport = builder.getMainThreadSupport();
        mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

    /**
     * 注册接收事件的Activity/Fragment为Subscribers到EventBus中
     * 在订阅者中通过@Subscribe的方式注解订阅事件的方法,可以指定线程模式,级别,sticky
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        //查找注册的Activity/Fragment中所有订阅方法,遍历
        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);
        //若集合为空,创建集合,添加这个新的newSubscription到集合
        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);
            }
        }

        //将新的订阅者信息newSubscription插入集合,按级别插入,要么就是最后一个位置
        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;
            }
        }

        //此新的订阅者Activity/Fragment订阅的所有事件类型集合
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        //存储新的订阅者Activity/Fragment订阅的事件
        subscribedEvents.add(eventType);

        //若订阅了sticky
        if (subscriberMethod.sticky) {
            //事件有父类或接口
            if (eventInheritance) {
                //sticky事件类型的set集合,
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    //一个事件类型
                    Class<?> candidateEventType = entry.getKey();
                    //若订阅的事件类型eventType是candidateEventType的父类或接口
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        //检查是否在主线程发送给订阅者
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                //sticky事件无父类或接口,直接获取sticky事件
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

    //检查是否在主线程发送给订阅者
    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());
        }
    }

    //指定线程模式发送给订阅者
    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);
        }
    }

    private boolean isMainThread() {
        return mainThreadSupport != null ? mainThreadSupport.isMainThread() : true;
    }

    public synchronized boolean isRegistered(Object subscriber) {
        return typesBySubscriber.containsKey(subscriber);
    }

    /** ondestory中解注册 */
    public synchronized void unregister(Object subscriber) {
        //此订阅者中的所有订阅事件类型
        List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
        if (subscribedTypes != null) {
            for (Class<?> eventType : subscribedTypes) {
                //从 事件类型 :所有订阅者 集合中移除这个订阅者
                unsubscribeByEventType(subscriber, eventType);
            }
            //从 订阅者;其订阅的事件 集合中移除key:订阅者
            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--;
                }
            }
        }
    }

    /** 发送事件到EventBus */
    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) {
            //查找此事件的类对象,包括它的父类和接口,添加到eventTypes
            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 static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
        //此事件类型 :此事件和它的父类,接口组成的集合
        synchronized (eventTypesCache) {
            List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
            //若为空,创建集合,存储当前的事件集合
            if (eventTypes == null) {
                eventTypes = new ArrayList<>();
                //当前事件
                Class<?> clazz = eventClass;
                while (clazz != null) {
                    //第一次,添加eventClass
                    eventTypes.add(clazz);
                    //递归查询多有接口,包括接口的接口,添加
                    addInterfaces(eventTypes, clazz.getInterfaces());
                    //向上查询父类,添加
                    clazz = clazz.getSuperclass();
                }
                eventTypesCache.put(eventClass, eventTypes);
            }
            return eventTypes;
        }
    }

    /** 递归查询多有接口,包括接口的接口,添加 */
    static void addInterfaces(List<Class<?>> eventTypes, Class<?>[] interfaces) {
        for (Class<?> interfaceClass : interfaces) {
            if (!eventTypes.contains(interfaceClass)) {
                eventTypes.add(interfaceClass);
                addInterfaces(eventTypes, interfaceClass.getInterfaces());
            }
        }
    }

    /** 取消发送事件 */
    public void cancelEventDelivery(Object event) {
        //当前发送线程状态
        PostingThreadState postingState = currentPostingThreadState.get();
        if (!postingState.isPosting) {
            throw new EventBusException(
                    "This method may only be called from inside event handling methods on the posting thread");
        } else if (event == null) {
            throw new EventBusException("Event may not be null");
        } else if (postingState.event != event) {
            throw new EventBusException("Only the currently handled event may be aborted");
        } else if (postingState.subscription.subscriberMethod.threadMode != POSTING) {
            throw new EventBusException(" event handlers may only abort the incoming event");
        }

        postingState.canceled = true;
    }

    /** 发送事件,缓存这个事件到stickyEvents,若有订阅者在之后订阅,还可收到stickyEvents中离
     *  订阅者最近的一个事件*/
    public void postSticky(Object event) {
        synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }

    /** 获取指定类型sticky事件 */
    public <T> T getStickyEvent(Class<T> eventType) {
        synchronized (stickyEvents) {
            return eventType.cast(stickyEvents.get(eventType));
        }
    }

    /** 移除指定类型sticky事件*/
    public <T> T removeStickyEvent(Class<T> eventType) {
        synchronized (stickyEvents) {
            return eventType.cast(stickyEvents.remove(eventType));
        }
    }

    /** 移除指定sticky事件,需判断它们是否有相同的class属性*/
    public boolean removeStickyEvent(Object event) {
        synchronized (stickyEvents) {
            Class<?> eventType = event.getClass();
            //以类型查找事件,看是否是同一个事件
            Object existingEvent = stickyEvents.get(eventType);
            if (event.equals(existingEvent)) {
                stickyEvents.remove(eventType);
                return true;
            } else {
                return false;
            }
        }
    }

    /**移除所有sticky事件*/
    public void removeAllStickyEvents() {
        synchronized (stickyEvents) {
            stickyEvents.clear();
        }
    }

    /** 是否有此事件的订阅者*/
    public boolean hasSubscriberForEvent(Class<?> eventClass) {
        //查找此事件的类对象,包括它的父类和接口
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        if (eventTypes != null) {
            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()) {
                    return true;
                }
            }
        }
        return false;
    }


    /**
     * 如果订阅为可发送状态,则调用订阅方。跳过订阅可以防止{@link #unregister(Object)}和事件交付之间的竞争条件。
     * 否则,事件可能在订阅者未注册后交付。这对于绑定到活动或片段的活动周期的主线程交付和注册尤其重要。
     */
    void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        //先存储即将发送事件pendingPost,释放事件池中的它
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            invokeSubscriber(subscription, event);
        }
    }

    /** 反射调用订阅者的订阅方法进行订阅*/
    void invokeSubscriber(Subscription subscription, Object event) {
        try {
            //反射调用subscriber的订阅方法method,订阅的事件为参数event
            subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
        } catch (InvocationTargetException e) {
            handleSubscriberException(subscription, event, e.getCause());
        } catch (IllegalAccessException e) {
            throw new IllegalStateException("Unexpected exception", e);
        }
    }

    private void handleSubscriberException(Subscription subscription, Object event, Throwable cause) {
        if (event instanceof SubscriberExceptionEvent) {
            if (logSubscriberExceptions) {
                // Don't send another SubscriberExceptionEvent to avoid infinite event recursion, just log
                logger.log(Level.SEVERE, "SubscriberExceptionEvent subscriber " + subscription.subscriber.getClass()
                        + " threw an exception", cause);
                SubscriberExceptionEvent exEvent = (SubscriberExceptionEvent) event;
                logger.log(Level.SEVERE, "Initial event " + exEvent.causingEvent + " caused exception in "
                        + exEvent.causingSubscriber, exEvent.throwable);
            }
        } else {
            if (throwSubscriberException) {
                throw new EventBusException("Invoking subscriber failed", cause);
            }
            if (logSubscriberExceptions) {
                logger.log(Level.SEVERE, "Could not dispatch event: " + event.getClass() + " to subscribing class "
                        + subscription.subscriber.getClass(), cause);
            }
            if (sendSubscriberExceptionEvent) {
                SubscriberExceptionEvent exEvent = new SubscriberExceptionEvent(this, cause, event,
                        subscription.subscriber);
                post(exEvent);
            }
        }
    }

    /** 在ThreadLocal存储的数据类 */
    final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<>();  //事件队列
        boolean isPosting;  //是否正在发送事件
        boolean isMainThread;   //是否主线程
        Subscription subscription;  //订阅者信息
        Object event;   //发送的事件
        boolean canceled;   //是否取消发送
    }

    ExecutorService getExecutorService() {
        return executorService;
    }

    /**
     * For internal use only.
     */
    public Logger getLogger() {
        return logger;
    }

    // Just an idea: we could provide a callback to post() to be notified, an alternative would be events, of course...
    /* public */interface PostCallback {
        void onPostCompleted(List<SubscriberExceptionEvent> exceptionEvents);
    }

    @Override
    public String toString() {
        return "EventBus[indexCount=" + indexCount + ", eventInheritance=" + eventInheritance + "]";
    }
}
 类似资料: