EventBus全解析系列(二)

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
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 162,825评论 4 377
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 68,887评论 2 308
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 112,425评论 0 255
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,801评论 0 224
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 53,252评论 3 299
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 41,089评论 1 226
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 32,216评论 2 322
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 31,005评论 0 215
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,747评论 1 250
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,883评论 2 255
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,354评论 1 265
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,694评论 3 265
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,406评论 3 246
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,222评论 0 9
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,996评论 0 201
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 36,242评论 2 287
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 36,017评论 2 281

推荐阅读更多精彩内容

  • 原文链接:http://blog.csdn.net/u012810020/article/details/7005...
    tinyjoy阅读 521评论 1 5
  • 先吐槽一下博客园的MarkDown编辑器,推出的时候还很高兴博客园支持MarkDown了,试用了下发现支持不完善就...
    Ten_Minutes阅读 549评论 0 2
  • 项目到了一定阶段会出现一种甜蜜的负担:业务的不断发展与人员的流动性越来越大,代码维护与测试回归流程越来越繁琐。这个...
    fdacc6a1e764阅读 3,111评论 0 6
  • EventBus源码理解 EventBus是我们在开发中经常使用的开源库,使用起来比较简单,而且源码看起来不是很吃...
    崔老板阅读 234评论 0 2
  • 博文出处:EventBus源码解析,欢迎大家关注我的博客,谢谢! 0001B 时近年末,但是也没闲着。最近正好在看...
    俞其荣阅读 1,256评论 1 16