EventBus源码分析

前言

EventBus是一个处理事件的第三方框架,以发布和订阅的方式让使用者能够避免一些复杂的逻辑,轻松地在组件之间传递消息。

EventBus is a publish/subscribe event bus for Android and Java.

这里写图片描述

我是17年底才接触到它的,所以这里就分析一下最新EventBus3.0的源码。至于如何使用EventBus,请进入github查看示例。

获取EventBus对象

    /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

注释已经写的很明白了,方便你在单一进程中获取一个全局范围的唯一实例

然而它的构造方法并没有私有化,我们也可以构造多个EventBus,当然一般情况下我们使用默认的即可。

    /**
     * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a
     * central bus, consider {@link #getDefault()}.
     */
    // 在应用中可以存在多个EventBus,它们之间相互独立,会发布和订阅各自的事件
    public EventBus() {
        this(DEFAULT_BUILDER);
    }

    EventBus(EventBusBuilder builder) {
        // 构造方法中进行了一系列的初始化操作,略过
        logger = builder.getLogger();
        subscriptionsByEventType = new HashMap<>();
        // 略过
        ……
    }

注册订阅者

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

注释中提示我们:

  1. 不需要接收消息的时候及时取消订阅
  2. 订阅的方法必须加上@Subscribe的注解
  3. 可以在@Subscribe中配置线程和订阅的优先级

查找订阅方法

我们进入findSubscriberMethods()

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        // 尝试从缓存中获取SubscriberMethod集合
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
        // 是否忽略注解器生成的MyEventBusIndex
        if (ignoreGeneratedIndex) {
            // 通过反射的方式获取subscriberMethods
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
            // 通过注解器生成的MyEventBusIndex信息获取subscriberMethods
            subscriberMethods = findUsingInfo(subscriberClass);
        }
        if (subscriberMethods.isEmpty()) {
            // 订阅者没有@Subscribe注解的方法会报错
            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;
        }
    }

这里先看findUsingInfo(),如果忽略注解器生成的MyEventBusIndex,会进入这个方法:

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        // 创建和初始化FindState对象
        // 进入prepareFindState(),发现用了一个数组作为对象池缓存了FindState,
        // 避免FindState的频繁创建
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        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对象当中 
                      findState.subscriberMethods.add(subscriberMethod);
                    }
                }
            } else {
                // 如果没有配置订阅者信息
                // 通过反射的方式来查找订阅方法
                findUsingReflectionInSingleClass(findState);
            }
            // 继续在父类查找订阅方法
            // 可以给findState.clazz重新赋值,进入下一个循环
            findState.moveToSuperclass();
        }
        // 返回订阅方法的集合,并且释放回收FindState对象
        return getMethodsAndRelease(findState);
    }

进入findUsingReflectionInSingleClass(),通过反射的方式来查找订阅方法:

    private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        // 这里的操作和findUsingInfo()中的基本一致
        // 主要是调用了findUsingReflectionInSingleClass()
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

进入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);
                    // 包含Subscribe的注解
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        // 保存到findState对象当中
                        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");
            }
        }
    }

订阅者订阅

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

进入subscribe()

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        // 获取订阅事件的类型
        Class<?> eventType = subscriberMethod.eventType;
        // 创建一个Subscription来保存订阅者和订阅方法
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        // 获取当前订阅事件对应的Subscription集合
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        if (subscriptions == null) {
            // 该事件对应的Subscription集合不存在
            // 则重新创建并保存在subscriptionsByEventType中
            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) {
                // 根据优先级,将newSubscription插入到对应的Subscription的集合中
                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);
            }
        }
    }

粘性事件

为什么在订阅阶段就处理事件了呢?从代码的逻辑思考反推,就是订阅者订阅的时候事件已经发送出来了

那么就很好理解粘性事件了,就是发布者发送一个粘性事件,这个事件会被存储起来,当对应的订阅者订阅这个事件时,立马就会接收到这个事件。

更简单的说,只要发送者发送过事件,订阅者在事件发送后才注册也能收到该事件。类似于,关机的手机突然开机了,能够收到之前关机阶段没收到的短信。

发布事件

进入post()

    /** Posts the given event to the event bus. */
    public void post(Object event) {
        // PostingThreadState保存着事件队列和线程状态信息
        // currentPostingThreadState是一个ThreadLocal对象,方便更快速地存取
        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;
            }
        }
    }

接着进入postSingleEvent()

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        // 获取事件的Class对象
        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));
            }
        }
    }

进入postSingleEventForEventType()

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            // 获取该事件对应的Subscription集合
            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;
    }

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

以上是根据订阅者订阅方法的线程来做不同的处理,默认的ThreadMode是POSTING,来看下ThreadMode

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.
     */
    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
}

应该还是比较好理解的。

最终都会进入invokeSubscriber()

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

当然也有可能调用不同的Poster,先把事件加入队列然后再去处理,Poster是个接口,有三个实现类HandlerPoster,BackgroundPoster,AsyncPoster,这里简单看一下他们的定义:

public class HandlerPoster extends Handler implements Poster

class AsyncPoster implements Runnable, Poster

final class BackgroundPoster implements Runnable, Poster

HandlerPoster所做的就是切换到主线程,然后再进一步处理事件。

取消注册

进入unregister()

    /** 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());
        }
    }

新特性Subscriber Index

利用apt避免了运行时寻找订阅者信息的反射操作,提高了性能,可以参考EventBus3.0新特性之Subscriber Index

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值