EventBus全解析系列(二)

作者: 嘎啦果安卓兽 | 来源:发表于2017-03-23 22:47 被阅读187次

    EventBus注册与反注册流程源码分析

        public void register(Object subscriber) {
            Class<?> subscriberClass = subscriber.getClass(); //获得订阅者的class
            List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass); // 查找订阅者类的所有订阅方法
            synchronized (this) {
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    subscribe(subscriber, subscriberMethod);
                }
            }
        }
    

    从上述代码可以看出,注册的大致流程为:

    1. 查找到订阅者类的所有订阅方法
    2. 注册订阅信息
      接下来我们来详细分析通过SubscriberMethodFinder来查找订阅方法的过程,在介绍之前我们先详细看一下SubscriberMethod
    public class SubscriberMethod {
        final Method method; // 订阅方法
        final ThreadMode threadMode; // 标识在哪个线程执行,有POSTING,MAIN,BACKGROUND,ASYNC 四种模式
        final Class<?> eventType; // 事件类
        final int priority; // 优先级
        final boolean sticky; // 是否是粘性事件
        /** Used for efficient comparison */
        String methodString; 
      ....
        }
    

    SubscriberMethod 包含了订阅方法相关的所有信息,接下来我们看SubscriberMethodFinder中是如何查找事件类中的所有订阅方法信息的

        List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
            List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass); //首先从METHOD_CACHE中读取缓存下来的订阅方法列表
            if (subscriberMethods != null) {
                return subscriberMethods;
            }
            // ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex。如何生成MyEventBusIndex类以及他的使用,可以本文中apt部分的详细说明。ignoreGeneratedIndex的默认值为false,可以通过EventBusBuilder来设置它的值
            if (ignoreGeneratedIndex) {
                // 利用反射来获取订阅类中所有订阅方法信息
                subscriberMethods = findUsingReflection(subscriberClass);
            } else {
                // 从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息
                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;
            }
        }
    

    从上面代码可以看出,SubscriberMethodFinder获得订阅方法信息列表的步骤为:

    1. 首先从订阅方法缓存中获取订阅类的订阅方法,如果没有则进入步骤2
    2. 通过ignoreGeneratedIndex属性判断通过以下两种方式中的一种来查找订阅方法,这两种方式为
      -如果ignoreGeneratedIndex为FALSE,通过EventBusAnnotationProcessor(注解处理器)生成的MyEventBusIndex中获取
      -否则通过反射来获取订阅类中订阅方法信息
      关于EventBusAnnotationProcessor注解处理器在本文中apt部分的介绍中有详细阐述,此处不再赘述。我们详细解读一下通过反射来获取订阅类中订阅方法信息列表的源代码
        private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
            FindState findState = prepareFindState(); 
            findState.initForSubscriber(subscriberClass); // 初始化FindState
            while (findState.clazz != null) { 
                findUsingReflectionInSingleClass(findState);// 寻找某个类中的所有事件响应方法
                findState.moveToSuperclass(); //继续寻找当前类父类中注册的事件响应方法
            }
            return getMethodsAndRelease(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) {
                int modifiers = method.getModifiers();
                // 找到所有声明为 public 的方法
                if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                    Class<?>[] parameterTypes = method.getParameterTypes(); // 找到方法参数并且参数数量为1
                    if (parameterTypes.length == 1) {
                        Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class); // 得到注解,并将方法添加到订阅信息中去
                        if (subscribeAnnotation != null) {
                            Class<?> eventType = parameterTypes[0];
                            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");
                }
            }
        }
    

    看一下FindState这个类,保存订阅者和订阅方法相关的信息,包括订阅类中所有订阅的事件类型和所有的订阅方法等信息。

        static class FindState {
            final List<SubscriberMethod> subscriberMethods = new ArrayList<>(); // 订阅方法信息列表
            final Map<Class, Object> anyMethodByEventType = new HashMap<>(); //以事件类型为key, 方法信息为value的集合 
            final Map<String, Class> subscriberClassByMethodKey = new HashMap<>(); // 以methodkey为key,订阅者类为value的集合
            final StringBuilder methodKeyBuilder = new StringBuilder(128); // 生成methodkey的stringbuilder
    
            Class<?> subscriberClass; // 订阅者类
            Class<?> clazz; 
            boolean skipSuperClasses; // 是否跳过父类
            SubscriberInfo subscriberInfo; 
    
            void initForSubscriber(Class<?> subscriberClass) {
                this.subscriberClass = clazz = subscriberClass;
                skipSuperClasses = false;
                subscriberInfo = null;
            }
    
            void recycle() {
                subscriberMethods.clear();
                anyMethodByEventType.clear();
                subscriberClassByMethodKey.clear();
                methodKeyBuilder.setLength(0);
                subscriberClass = null;
                clazz = null;
                skipSuperClasses = false;
                subscriberInfo = null;
            }
        // checkAdd这部分的作用是检测订阅者中注册的事件响应方法是否可以合法的加入到订阅方法信息中,分为两层检查
            boolean checkAdd(Method method, Class<?> eventType) {
                // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.
                // Usually a subscriber doesn't have methods listening to the same event type.
                //第一次检查同一事件类型下是否已有订阅方法信息
                Object existing = anyMethodByEventType.put(eventType, method);
                if (existing == null) {
                    return true;//如果还未有订阅方法监听此事件,则可添加此订阅方法信息
                } else {
                    if (existing instanceof Method) {
                    // 检测到同一事件类型下已经有订阅事件响应方法,则继续进行方法签名的检查
                        if (!checkAddWithMethodSignature((Method) existing, eventType)) {
                            // Paranoia check
                            throw new IllegalStateException();
                        }
                        // Put any non-Method object to "consume" the existing Method
                        anyMethodByEventType.put(eventType, this);
                    }
                    return checkAddWithMethodSignature(method, eventType);
                }
            }
            // 使用订阅方法签名检测是否可以加入订阅方法信息列表
            private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
                methodKeyBuilder.setLength(0);
                methodKeyBuilder.append(method.getName());
                methodKeyBuilder.append('>').append(eventType.getName());//使用订阅方法名以及订阅事件类型构造methordKey
    
                String methodKey = methodKeyBuilder.toString();
                Class<?> methodClass = method.getDeclaringClass();
                Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass); //判断是否存方法签名相同的事件响应方法,并比较相同方法签名的订阅方法所在类的关系
                if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {
                    // Only add if not already found in a sub class
                    // 如果不存在同样方法签名的订阅方法或者,之前保存的订阅方法所在的类为当前将要添加的订阅方法所在的类的子类(目前不存在此情况,因为只会从子类向父类查找),则可以合法添加此订阅方法信息
                    return true;
                } else {
                    // Revert the put, old class is further down the class hierarchy
                    //subscriberClassByMethodKey只保存父子继承关系的最下层子类,目的是为了在子类注册监听事件时,如果父类中有相同的事件响应方法,应该调用子类的覆写方法。
                    subscriberClassByMethodKey.put(methodKey, methodClassOld);
                    return false;
                }
            }
    
            void moveToSuperclass() {
                if (skipSuperClasses) {
                    clazz = null;
                } else {
                    clazz = clazz.getSuperclass();
                    String clazzName = clazz.getName();
                    /** Skip system classes, this just degrades performance. */
                    if (clazzName.startsWith("java.") || clazzName.startsWith("javax.") || clazzName.startsWith("android.")) {
                        clazz = null;
                    }
                }
            }
        }
    
    

    分析以上源码,具体步骤如下:

    1. 通过反射得到当前 class 的所有方法
    2. 过滤掉不是 public 和是 abstract、static、bridge、synthetic 的方法
    3. 找出所有参数只有一个的方法
    4. 找出被Subscribe注解的方法
    5. 把method 方法和 事件类型eventtype添加到 findState 中
    6. 把 method 方法、事件类型、threadMode、priority、sticky 封装成 SubscriberMethod 对象,然后添加到 findState.subscriberMethods
      以上为查找订阅者类中所有订阅方法信息的详细过程,查找完订阅类中所有订阅方法信息后,遍历所有订阅方法信息,继续进行注册的步骤
        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);
                }
            }
        }
    

    以上代码的流程如下:

    1. 如果当前订阅信息没有注册过,则按照优先级加入到订阅信息集合 subscriptionsByEventType(subscriptionsByEventType以事件类为key,以订阅信息列表为value的订阅信息集合)。
    2. 将事件类型加入到订阅事件类型集合 typesBySubscriber(typesBySubscriber 以订阅者对象为key,以订阅事件类型为value的订阅类型信息集合)。
    3. 如果当前订阅的为粘性事件,则进入事件分发的流程。
      Map<Class<?>, Object> stickyEvents; 以事件类为key,以事件对象为value的粘性事件集合
      Subscription是订阅信息类,包含订阅者对象,订阅方法,是否处于激活状态等
    final class Subscription {
        final Object subscriber; // 订阅者对象
        final SubscriberMethod subscriberMethod;  // 订阅方法
        /**
         * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
         * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
         */
        volatile boolean active; // 是否处于激活状态
    
        Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
            this.subscriber = subscriber;
            this.subscriberMethod = subscriberMethod;
            active = true;
        }
    
        @Override
        public boolean equals(Object other) {
            if (other instanceof Subscription) {
                Subscription otherSubscription = (Subscription) other;
                return subscriber == otherSubscription.subscriber
                        && subscriberMethod.equals(otherSubscription.subscriberMethod);
            } else {
                return false;
            }
        }
    
        @Override
        public int hashCode() {
            return subscriber.hashCode() + subscriberMethod.methodString.hashCode();
        }
    }
    

    总结如上代码流程,注册的流程图如下:

    eventbus流程图.png

    反注册流程源码详解

        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 {
                Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());
            }
        }
    
        private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
            List<Subscription> subscriptions = subscriptionsByEventType.get(eventType); // 获取事件类的所有订阅信息列表,将订阅信息从订阅信息集合中移除,同时将订阅信息中的active属性置为FALSE
            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; // 将订阅信息激活状态置为FALSE
                        subscriptions.remove(i); // 将订阅信息从集合中移除
                        i--;
                        size--;
                    }
                }
            }
        }
    

    反注册的流程为:

    1. 将订阅者的订阅信息从订阅信息集合中移除,同时将订阅信息激活状态置为FALSE
    2. 将订阅者信息从订阅者订阅类型集合中移除

    总结如上代码流程,注册的流程图如下:

    Paste_Image.png

    相关文章

      网友评论

        本文标题:EventBus全解析系列(二)

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