EventBus - 7 源码解析-5:register订阅(下)

这篇文章,主要分析一下checkAdd这个方法:

if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
    findState.subscriberMethods.add(subscriberMethod);
}

这个checkAdd方法,主要判断 subscriberMethod订阅好的方法,是否可以添加到 subscriberMethods订阅方法的集合当中。

接下来我们来看下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.
            // 返回的是之前的value,也就是之前的那个方法
            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);
            }
        }
但是 大家需要注意的一点是,在EventBus当中,它有一个特点,它一个订阅者,包括这个订阅者所有的父类和子类,
它不会有多个方法,相同的全部去接收同一个事件。
         
但是可能会出现这样一种情况,什么情况呢 ?
         
子类去订阅该事件,同时 父类也去订阅该事件,当这样一种情况出现,
我们的在EventBus是如何来判断的呢 ?
         

它会走到 checkAddWithMethodSignature(method, eventType) 方法这里。

private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {
            methodKeyBuilder.setLength(0);
            methodKeyBuilder.append(method.getName());
            methodKeyBuilder.append('>').append(eventType.getName());

            String methodKey = methodKeyBuilder.toString();
            Class<?> methodClass = method.getDeclaringClass();
            // 本方法为key,订阅好的类Class对象为value
            Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);
            // 如果Class对象不存在,或者这个值是我们method父类的话,这个时候就返回true
            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
                /**
                 * 这个中心思想就是,我们不要出现一个订阅者,有多个相同方法,订阅同一个事件,
                 * 如果有的话,我们就把以前的Class放到HashMap当中去覆盖。
                 *
                 */
                subscriberClassByMethodKey.put(methodKey, methodClassOld);
                return false;
            }
        }




                    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值