美文网首页
EventBus源码全流程解读

EventBus源码全流程解读

作者: 一坨坨的叶俊杰 | 来源:发表于2019-09-25 09:51 被阅读0次

    目录

    • EventBus优缺点

    • EventBus基本用法

    • EventBus源码解析

    一、EventBus优缺点对比

    优点:
    1、是一个轻量级的事件总线,使用方便
    2、去除应用中大量的回调,能一定程度解耦各组件

    缺点:
    1、代码可读性降低,大量的事件使代码解耦的同时,联系也变得弱了
    2、不支持跨进程通讯(广播支持)

    二、EventBus使用

    首先使用别人家的东西第一步导包:

    implementation 'org.greenrobot:eventbus:3.1.1'
    

    EventBus使用相对简单,github下面就有使用步骤,我们直接参照


    EventBus官方使用步骤说明.png

    1.定义传递的时间对象,该对象就是步骤2中接收的对象,也是步骤3中发送的事件
    2.(1)定义接收事件方法(即订阅方法),该方法用注解@Subscribe修饰,并通过threadMode指定其分发到的线程 (2)在定义接收方法的类中(Android中一般为activity、fragment或service)注册与解注册EventBus
    3.在任何地方通过post方法发送你的事件
    通过以上三个步骤就可以使用EventBus进行事件传递

    三、源码分析

    在分析源码之前我们有几个问题需要抛出
    1、EventBus是如何确定哪些方法是订阅方法的
    2、EventBus是如何做线程切换的
    3、EventBus为什么不支持跨进程
    如果读完这篇源码分析能解决以上问题就足够了

    1.EventBus对象

    EventBus.java

    static volatile EventBus defaultInstance;
    //双重检查锁获取单例对象
    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;
        }
    

    EventBus.getDefault()通过双重检查锁获取单例对象,并通过volatile关键字保证单例对象的可见性

    2.register与unregister

    (1) register

    /**
         * 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();
            //1、SubscriberMethod为已订阅的方法,这里通过类对象查找到该类所有订阅方法  
            List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
            //2、遍历该类所有已订阅方法,并订阅  
            synchronized (this) {
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    subscribe(subscriber, subscriberMethod);
                }
            }
        }
    

    上面代码也很好理解,
    (1)根据类对象获得该类中定义的订阅方法信息
    (2)遍历所有订阅方法执行订阅
    下面针对这两个问题我们具体进去看看
    SubscriberMethodFinder.java

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

    这里主要根据ignoreGeneratedIndex标志位判断调用哪个方法获取订阅方法,ignoreGeneratedIndex标志位使用的是EventBusBuilder的默认实例,EventBusBuilder的ignoreGeneratedIndex默认为false,因此这里会执行findUsingInfo(subscriberClass)

    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
            FindState findState = prepareFindState();
            findState.initForSubscriber(subscriberClass);
            //1、循环遍历该类及其父类的方法
            while (findState.clazz != null) {
                //获取已订阅信息缓存
                findState.subscriberInfo = getSubscriberInfo(findState);
                //2、判断订阅方法是否为空,为空通过反射获取订阅方法;不为空直接使用缓存
                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 {
                    findUsingReflectionInSingleClass(findState);
                }
                findState.moveToSuperclass();
            }
            return getMethodsAndRelease(findState);
        }
    

    这里通过FindState对象保存需要的信息,通过遍历该类及其所有父类获取所有订阅方法,订阅信息如已存在于缓存中,直接取出使用;如果为缓存中没有,使用反射获取。下面我们着重看看反射获取订阅方法的相关内容

    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) {
                //1、判断方法必须是public修饰,且不是static也不是abstract修饰的
                int modifiers = method.getModifiers();
                if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                    //2、获取方法入参,判断入参只有一个,继续执行(表示订阅方法只能有一个入参)
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    if (parameterTypes.length == 1) {
                        //3、获取注解,判断注解不为空则继续执行(表示订阅方法必须由Subscribe注解)
                        Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                        if (subscribeAnnotation != null) {
                            Class<?> eventType = parameterTypes[0];
                            if (findState.checkAdd(method, eventType)) {
                                //获取直接中threadMode参数,该参数为订阅方法执行的线程定义
                                ThreadMode threadMode = subscribeAnnotation.threadMode();
                                //4、以上全部符合要求,将信息保存到findState中
                                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");
                }
            }
        }
    

    通过findUsingReflectionInSingleClass方法我们可以看到EventBus对订阅方法的约束:
    1、订阅方法必须是public修饰的,且不能用static、abstract修饰
    2、订阅方法的参数只能是一个,即事件对象
    3、订阅方法必须有@ Subscribe注解 ,threadMode默认为POSTING

    分析完订阅方法的获取,我们具体看看这些方法是如何订阅的

        //根据事件类型(eventType),保存所有eventType的订阅方法
        private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
        //根据订阅对象(subscriber),保存该订阅对象的所有事件
        private final Map<Object, List<Class<?>>> typesBySubscriber;
        // 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);
            /**
             *  1、判断该事件是否已有存储订阅方法信息的容器;
             *  没有则创建容器,并将容器存入subscriptionsByEventType中;
             *  若存在判断该订阅方法(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);
                }
            }
            
            int size = subscriptions.size();
            //2、根据优先级将订阅方法(newSubscription)插入容器对用的位置
            for (int i = 0; i <= size; i++) {
                if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
                    subscriptions.add(i, newSubscription);
                    break;
                }
            }
            //3、根据注册对象subscriber保存该对象所有事件(实际subscribedEvents缓存的信息代表该注册对象subscriber是否被注册)
            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);
                }
            }
        }
    

    subscribe方法总共有做了几件事:
    1、通过eventType将该eventType下所有订阅方法保存在subscriptionsByEventType中
    2、通过订阅对象将该订阅对象所拥有的所有eventType对象保存在typesBySubscriber中
    3、判断是否是粘性事件并做对应的处理(这里我们不做分析)

    看到这里肯定有很多的疑惑:
    1、subscriptionsByEventType这个map是做什么的?
    2、typesBySubscriber这个map又是做什么的?
    这里我们先揭晓答案:
    1、subscriptionsByEventType实际是通过eventType保存该eventType所有的订阅方法,这里理解为实际的订阅;待事件分发时再根据eventType从subscriptionsByEventType中获取订阅方法进行分发(后面post中会分析)
    2、typesBySubscriber通过注册对象保存该注册对象所有的事件;这里保存代表为实际注册,待解注册时,再讲该注册对象的eventType从typesBySubscriber中移除,这个在unregister中可以体现

    (2) unregister
    接下来我们就来看看unregister方法:

    /** Unregisters the given subscriber from all event classes. */
        public synchronized void unregister(Object subscriber) {
            //1、获取缓存中注册对象所有事件类型,遍历并解订阅事件
            List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);
            if (subscribedTypes != null) {
                for (Class<?> eventType : subscribedTypes) {
                    unsubscribeByEventType(subscriber, eventType);
                }
                //全部事件解订阅后,删除typesBySubscriber中的类对象,实际这里表示解注册
                typesBySubscriber.remove(subscriber);
            } else {
                logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
            }
        }
    

    分析代码可以知道,解注册实际做了两件事
    1、解订阅所有的订阅事件,及遍历执行unsubscribeByEventType()方法
    2、订阅类移除map列表中,即typesBySubscriber.remove(subscriber)
    unsubscribeByEventType()方法通过名称已经很明显;无非就是将注册时保存在subscriptionsByEventType中的订阅方法移除;具体代码贴出,但并没有太值得阅读的地方

    /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
        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--;
                    }
                }
            }
        }
    

    3.post方法

    刚刚已经分析register方法,发现register其实最主要的就是将所有已注册对象中的订阅方法保存在subscriptionsByEventType这个map中,那post自然就是遍历subscriptionsByEventType这个map然后执行对应的分发。

    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
            @Override
            protected PostingThreadState initialValue() {
                return new PostingThreadState();
            }
        };
        /** Posts the given event to the event bus. */
        public void post(Object event) {
            //1、使用ThreadLocal获取当前线程参数
            PostingThreadState postingState = currentPostingThreadState.get();
            List<Object> eventQueue = postingState.eventQueue;
            //将事件加入List队列中
            eventQueue.add(event);
            //2、判断当前线程post状态
            if (!postingState.isPosting) {
                postingState.isMainThread = isMainThread();
                postingState.isPosting = true;
                if (postingState.canceled) {
                    throw new EventBusException("Internal error. Abort state was not reset");
                }
                try {
                    //3、postSingleEvent处理单个事件
                    while (!eventQueue.isEmpty()) {
                        postSingleEvent(eventQueue.remove(0), postingState);
                    }
                } finally {
                    //4、恢复post线程状态
                    postingState.isPosting = false;
                    postingState.isMainThread = false;
                }
            }
        }
    

    这段代码主要是判断当前线程post状态,如果有正在分发中的事件,则将新事件置入事件池排队等待执行;如果没有,则将事件加入队列并执行。其核心代码为postSingleEvent(eventQueue.remove(0), postingState) 所以我们继续看看postSingleEvent做了些什么事

    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
            Class<?> eventClass = event.getClass();
            boolean subscriptionFound = false;//该属性判断是否存在待分发事件的订阅方法
            if (eventInheritance) {//eventInheritance为默认Builder中的值,默认为true
                //找到当前待分发事件的所有事件类型(这里包括父类、接口类等)
                List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
                int countTypes = eventTypes.size();
                for (int h = 0; h < countTypes; h++) {
                    Class<?> clazz = eventTypes.get(h);
                    //1、postSingleEventForEventType通过事件类型查找是否有对应的订阅方法
                    subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
                }
            } else {
                subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
            }
            //2、如果没有找到对应的订阅方法,发送一个默认事件
            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));
                }
            }
        }
    

    1、判断是否找到待分发事件的订阅方法,找到则分发事件,其核心代码为subscriptionFound |= postSingleEventForEventType(event, postingState, clazz)
    2、未找到则默认发送一个默认的事件,post(new NoSubscriberEvent(this, event))

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
            CopyOnWriteArrayList<Subscription> subscriptions;
            synchronized (this) {
                //1、在subscriptionsByEventType中获取该事件对应订阅方法的集合
                subscriptions = subscriptionsByEventType.get(eventClass);
            }
            if (subscriptions != null && !subscriptions.isEmpty()) {
                //2、遍历集合,并执行分发事件至具体的已订阅方法中
                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;
        }
    

    这里的主要逻辑如下
    1、通过事件类对象在subscriptionsByEventType这个map中取出该事件的所有订阅类集合,subscriptionsByEventType中的订阅方法集合是在注册是添加的,我们在分析register源码时已经分析了;
    2、取出该事件订阅方法合集之后就是遍历所有的订阅方法并分发,该过程核心代码为:postToSubscription(subscription, event, postingState.isMainThread)
    说了那么久才真正的进入post最核心的地方--事件分发,到目前为止我们知道post进入时会根据当前线程获取一个缓存信息类postingState对象,其不同线程有通的队列处理消息分发;但是我们都知道EventBus中是帮我们做了线程切换的,我们可以通过@ Subscribe注解的threadMode属性指定订阅方法执行的线程;那这一块的具体逻辑应该就是在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进行判断:
    PSOTING:直接反射调用订阅方法;该模式表示在哪个线程发布事件就在哪个线程处理
    MAIN:如果当前post线程为主线程直接反射调用方法(防止主线程阻塞),如果post线程不是主线程,则调用mainThreadPoster排队处理;该模式表示在主线程调用订阅方法
    MAIN_ORDERED:因为mainThreadPoster不会为null所以一直会排队处理,并且会回调到主线程处理;该模式表示在主线程中排队处理(即等待上一个时间处理后再发送下一个事件)
    BACKGROUND:如果当前post线程为主线程,开启一个新的后台线程处理分发,如果当前post线程不为主线程,则直接反射调用;该模式表示事件一直在后台线程中处理
    ASYNC:由asyncPoster排队处理;该模式表示不管post线程是否为主线程,都会新开一个异步线程处理

    这边可以总结得出,部分情况直接反射调用订阅方法;部分根据情况开启对应的线程处理;如mainThreadPoster实际是Handler子类,通过handler机制切换回主线程,backgroundPoster、asyncPoster实际实现了Runable接口,在子线程中执行;他们主要的工作只是线程切换,切换后最终都会通过EventBus的反射方法地调用订阅方法 eventBus.invokeSubscriber(pendingPost)
    反射方法如下:
    其中带一个入参的反射方法就是供线程切换后调用的反射方法

    /**
         * Invokes the subscriber if the subscriptions is still active. Skipping subscriptions prevents race conditions
         * between {@link #unregister(Object)} and event delivery. Otherwise the event might be delivered after the
         * subscriber unregistered. This is particularly important for main thread delivery and registrations bound to the
         * live cycle of an Activity or Fragment.
         */
        void invokeSubscriber(PendingPost pendingPost) {
            Object event = pendingPost.event;
            Subscription subscription = pendingPost.subscription;
            PendingPost.releasePendingPost(pendingPost);
            if (subscription.active) {
                invokeSubscriber(subscription, event);
            }
        }
    
        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);
            }
        }
    

    至此我们的源码分析就结束了,现在让我们回到开始的那几个问题
    1、EventBus是如何确定哪些方法是订阅方法的
    答:通过源码分析知道,EventBus注册是传入一个类对象,然后对类对象的所有方法(包括其父类的所有方法)进行遍历,然后根据一定的规则过滤订阅方法,分析过程中已列出,可以重新查看SubscriberMethodFinder类中的findUsingReflectionInSingleClass()方法;
    2、EventBus是如何做线程切换的
    答:通过Handler由子线程切换到主线程;通过实现Runable接口,切换至子线程处理,线程切换后通过反射调用订阅方法分发事件
    3、EventBus为什么不支持跨进程
    答:咋一看我们好像没有再源码中分析这一问题,其实这是一个需要理解的问题;首先我们需要理解Android的沙箱隔离机制,Android中为了各应用的安全,不允许应用直接访问其他应用,所以Android中应用通讯就需要另一个技术实现--IPC跨进程通讯,我们回想下EventBus注册时保存的订阅方法的map集合,是保存在内存中的,我们Post发送事件时也是直接在内存中取出map中的方法,整个过程数据都涉及任何的IPC通讯。所以自然无法做到跨进程调用

    相关文章

      网友评论

          本文标题:EventBus源码全流程解读

          本文链接:https://www.haomeiwen.com/subject/yrdructx.html