美文网首页
EventBus3.1源码分析

EventBus3.1源码分析

作者: jh352160 | 来源:发表于2018-04-08 20:05 被阅读27次

    这篇文章将会为大家梳理一下EventBus的基本流程,本人使用的版本号为3.1.1,为了方便阅读,文章中的源码部分将省略部分有关异常捕获与日志相关代码。

    使用示例

    首先,按照官方的文档来看看一个最简单的EventBus示例是什么样的:

    第一步:定义消息实体类

    public class MessageEvent {
        public final String message;
        
        public MessageEvent(String message) {
            this.message = message;
        }
    }
    

    第二步:使用注解创建订阅方法

    @Subscribe
    public void onMessageEvent(MessageEvent event) {
        Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
    }
    

    第三步:注册与注销订阅(注意与生命周期的绑定)

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }
     
    @Override
    public void onStop() {
        EventBus.getDefault().unregister(this);
        super.onStop();
    }
    

    第四步:发送通知消息

    EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
    

    这样,一个简单的Demo就完成了,本文将以这个Demo为基础,分析订阅事件从注册到接收并执行都是如何实现的。

    1.EventBus.getDefault().register(this);

    EventBus.getDefault()

        static volatile EventBus defaultInstance;
    
        public static EventBus getDefault() {
            if (defaultInstance == null) {
                synchronized (EventBus.class) {
                    if (defaultInstance == null) {
                        defaultInstance = new EventBus();
                    }
                }
            }
            return defaultInstance;
        }
    

    获取EventBus的单例对象,很标准的单例模式,就不细说了。

    EventBus.register(Object subscriber)

        public void register(Object subscriber) {
            //获取注册订阅的类的Class对象
            Class<?> subscriberClass = subscriber.getClass();
            //查找Class中带有Subscribe注解的方法列表
            List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
            synchronized (this) {
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    subscribe(subscriber, subscriberMethod);
                }
            }
        }
    

    SubscriberMethodFinder.findSubscriberMethods(Class<?> subscriberClass)

        List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
            //METHOD_CACHE为ConcurrentHashMap<Class<?>, List<SubscriberMethod>>,作为方法解析的缓存使用
            List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
            //如果取出的SubscriberMethod不为null,则说明该类已被加载过,那么跳过解析的步骤,直接返回上次解析的结果
            if (subscriberMethods != null) {
                return subscriberMethods;
            }
    
            //ignoreGeneratedIndex用来设置是否忽略使用Subscriber Index来帮助注解解析,默认设置为false
            //Subscriber Index为EventBus3.0中出现的新特性,在build期间生成,以此增加注解解析的性能
            //关于Subscriber Index的更多信息可以参考官方文档 http://greenrobot.org/eventbus/documentation/subscriber-index/
            if (ignoreGeneratedIndex) {
                subscriberMethods = findUsingReflection(subscriberClass);
            } else {
                subscriberMethods = findUsingInfo(subscriberClass);
            }
            if (subscriberMethods.isEmpty()) {
                //如果类中没有找到Subscriber注解的方法,抛出异常
                throw new EventBusException("Subscriber " + subscriberClass
                        + " and its super classes have no public methods with the @Subscribe annotation");
            } else {
                //将Subscriber注解的方法放入缓存并返回
                METHOD_CACHE.put(subscriberClass, subscriberMethods);
                return subscriberMethods;
            }
        }
    

    从这个方法可以看出EventBus会将注册的订阅事件以Class对象为key,订阅方法的Method对象为value存入METHOD_CACHE缓存中,避免同一个类多次注册订阅时重复解析的问题,提升解析的性能。

    在注解解析方面,EventBus提供了传统的反射解析与使用Subscriber Index两种方式,下面将主要对反射解析方式分别进行分析

    SubscriberMethodFinder.findUsingReflection(Class<?> subscriberClass)

        private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
            //通过FindState对象池创建FindState对象
            FindState findState = prepareFindState();
            //初始化FindState对象
            findState.initForSubscriber(subscriberClass);
            
            while (findState.clazz != null) {
                //解析这个类中带有Subscribe注解的方法
                findUsingReflectionInSingleClass(findState);
                //向父类进行遍历
                findState.moveToSuperclass();
            }
            //获取解析出的方法,将findState重置并放回对象池中
            return getMethodsAndRelease(findState);
        }
        
        private void findUsingReflectionInSingleClass(FindState findState) {
            Method[] methods;
            try {
                // This is faster than getMethods, especially when subscribers are fat classes like Activities
                //getDeclaredMethods方法只会获取到该类所定义的方法,而getMethods方法会获取包括这个类的父类与接口中的所有方法
                methods = findState.clazz.getDeclaredMethods();
            } catch (Throwable th) {
                // Workaround for java.lang.NoClassDefFoundError, see https://github.com/greenrobot/EventBus/issues/149
                // 使用getMethods就已经获得了其父类的所有方法,所以将skipSuperClasses标志位设置为true,在后续过程中不对其父类进行解析
                methods = findState.clazz.getMethods();
                findState.skipSuperClasses = true;
            }
            for (Method method : methods) {
                int modifiers = method.getModifiers();
                //Subscribe注解的方法不应为私有且不应为抽象,静态等
                if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    //Subscribe注解的方法应有且只有一个参数
                    if (parameterTypes.length == 1) {
                        Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                        if (subscribeAnnotation != null) {
                            Class<?> eventType = parameterTypes[0];
                            //调用checkAdd方法判断是否将订阅事件添加进订阅列表中
                            if (findState.checkAdd(method, eventType)) {
                                ThreadMode threadMode = subscribeAnnotation.threadMode();
                                findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                        subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                            }
                        }
                    }
                }
            }
        }
    

    在这段代码中出现了一个FindState类对象,其中含有解析相关的配置,解析出的方法等等,整个解析的过程都是围绕着这个对象进行处理。

    FindState.checkAdd

        final Map<Class, Object> anyMethodByEventType = new HashMap<>();
        final StringBuilder methodKeyBuilder = new StringBuilder(128);
        final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
    
        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);
            // 第一级判断,如果existing为null,则代表该eventType为首次添加,直接返回true
            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
                    // 该方法只为了将一个不是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());
    
            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
                // 撤销之前的put操作,并返回false
                subscriberClassByMethodKey.put(methodKey, methodClassOld);
                return false;
            }
        }
    

    这部分代码的作用主要有两点:

    1. 当一个类重载了父类的一个订阅方法,在向上级父类遍历时跳过父类中的这个方法的订阅,也就是说以子类的订阅方法为准
    2. 允许一个类有多个方法名不同的方法对同个事件进行订阅

    值得一提的是关于methodClassOld.isAssignableFrom(methodClass)这一句代码,有文章提到因为之前的代码中会使用Class.getMethods()方法,会得到这个类以及父类的public方法,所以这句代码的结果可能为true,但是经我测试,如果父类方法被子类重载,那么getMethods方法得到的只会有子类的重载方法一个,父类的方法并不会出现,所以从这方面来说,这句代码依然只能是false。

    EventBus.register(Object subscriber, SubscriberMethod subscriberMethod)

        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;
                }
            }
    
            //将参数类型以订阅者对象为key,参数类型列表为value保存进一个Map中
            List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
            if (subscribedEvents == null) {
                subscribedEvents = new ArrayList<>();
                typesBySubscriber.put(subscriber, subscribedEvents);
            }
            subscribedEvents.add(eventType);
            //对于一般的事件的注册,到这里就已经完成了
            //-----------------------------------------------------------------------------
            
            //针对粘性事件订阅者的处理
            if (subscriberMethod.sticky) {
                //eventInheritance:是否支持事件继承,默认为true。当为true时,post一个事件A时,若A是B的父类,订阅B的订阅者也能接收到事件。
                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);
                }
            }
        }
    

    到现在为止,其实已经可以总结出EventBus中订阅者注册的核心逻辑了,就是筛选出注册的类中带有Subscribe注解的方法,然后将其解析为SubscriberMethod对象,以订阅的事件类型为key,SubscriberMethod对象为value的形式存入subscribedEvents中。

    对于粘性事件的发送,其实与之后的一般事件执行逻辑相同,这里就不再深入了。

    EventBus.getDefault().post(new MessageEvent("Hello everyone!"))

    EventBus.post(Object event)

        public void post(Object event) {
            //从ThreadLocal中取出PostingThreadState对象,PostingThreadState对象只是保存一些消息发送过程中需要的信息
            //使用ThreadLocal保证PostingThreadState对象在各线程间相互独立,以此实现线程安全
            PostingThreadState postingState = currentPostingThreadState.get();
            //从PostingThreadState对象中取出当前线程的消息队列,并将需要发送的消息加入队列中
            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 {
                    //遍历结束,重置PostingThreadState对象
                    postingState.isPosting = false;
                    postingState.isMainThread = false;
                }
            }
        }
    

    在这段代码中,isMainThread()方法可以用来判断消息发送是否是在主线程中。其中的逻辑非常简单,通过Looper类中的getMainLooper()获取到主线程中的Looper对象,然后再通过Looper类中的myLooper()方法获取当前线程的Looper对象,然后相互比较。

    EventBus.postSingleEvent(Object event, PostingThreadState postingState)

        private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
            Class<?> eventClass = event.getClass();
            boolean subscriptionFound = false;
            //如果该消息支持事件继承,则获取该消息类型的所有父类与接口类型,并分别调用postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass)方法
            if (eventInheritance) {
                //获取消息类型的所有父类与接口
                List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
                int countTypes = eventTypes.size();
                //对于ArrayList而言,使用基本的for循环实现遍历效率更高
                for (int h = 0; h < countTypes; h++) {
                    Class<?> clazz = eventTypes.get(h);
                    subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
                }
            } else {
                subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
            }
            
            //如果该消息没有订阅者,则根据配置输出相应的log或发送消息
            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));
                }
            }
        }
    

    EventBus.postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass)

        private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
            CopyOnWriteArrayList<Subscription> subscriptions;
            synchronized (this) {
                //从Map中将该消息的订阅事件列表取出
                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;
        }
    

    这个方法的主要作用就是获得消息的订阅事件列表,完成对于postingState中参数的赋值,其中对于所有的订阅事件,使用的其实是同一个PostingThreadState对象,只是对于不同的订阅事件,会改变其中的部分参数的值。

    EventBus.postToSubscription(Subscription subscription, Object event, boolean isMainThread)

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

    在默认情况下,EventBus会在调用线程中直接执行invokeSubscriber方法调用订阅事件,但当调用线程与期望的执行线程不一致或希望异步调用时,使用Poster来进行不同线程间的调度,每一个Poster中都会持有一个消息队列,并在指定线程执行。

    EventBus.invokeSubscriber(Subscription subscription, Object event)

        void invokeSubscriber(Subscription subscription, Object event) {
            try {
                subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
            } catch (InvocationTargetException e) {
                //如果捕获到InvocationTargetException异常,则根据配置打印Log或发送异常消息
                handleSubscriberException(subscription, event, e.getCause());
            } catch (IllegalAccessException e) {
                throw new IllegalStateException("Unexpected exception", e);
            }
        }
    

    这段代码也就是订阅事件执行部分的最后一段代码了,可以看到逻辑非常的简单,就是通过反射来执行相应的订阅事件。

    总结

    在上文的分析中可以看出,EventBus的主要逻辑非常简单,核心流程就是注册时先解析出带有相应注解的方法,然后将其的Method对象与其所订阅的消息类型绑定加入到一个集合中,然后发送消息时获取到消息类型所对应的订阅事件的Method对象,通过反射来调用执行。

    相关文章

      网友评论

          本文标题:EventBus3.1源码分析

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