美文网首页
事件总线-EventBus-源码学习过程

事件总线-EventBus-源码学习过程

作者: 风筝李 | 来源:发表于2016-11-08 00:02 被阅读0次

    使用过程略过。

    源码分析

    register方法:
    1、获取注册对象类型
    2、获取对象的所有的订阅方法的集合
    3、遍历集合,执行订阅subscribe方法。

    /**
         * 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();
            List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
            synchronized (this) {
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    subscribe(subscriber, subscriberMethod);
                }
            }
        }
    

    SubscriberMethod类包含订阅方法的所有信息,Method对象,参数类型,执行的线程,优先级,是否粘性

    public class SubscriberMethod {
        final Method method;//Method
        final ThreadMode threadMode;//执行的线程
        final Class<?> eventType;//方法参数的EventType
        final int priority;//优先级
        final boolean sticky;//是否粘性
        /** Used for efficient comparison */
        String methodString;//用于比较的字段
    
        public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
            this.method = method;
            this.threadMode = threadMode;
            this.eventType = eventType;
            this.priority = priority;
            this.sticky = sticky;
        }
    ......其他代码省略
    }
    

    SubscriberMethod集合的获取逻辑:

    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    

    findSubscriberMethods实现

        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;
            }
        }```
    分为使用索引和忽略索引两个方法的内容,使用索引的后面单独了解。忽略索引的逻辑,FindState查找帮助类。里面的checkAll、checkAddWithMethodSignature、moveToSuperclass这三个方法很有趣,使用的map.put返回“前任”逻辑,巧妙的实现了对象是否被添加过的判断。
    

    static class FindState {
    //所有订阅方法的集合
    final List<SubscriberMethod> subscriberMethods = new ArrayList<>();
    //事件类型是已经存在的标识map
    final Map<Class, Object> anyMethodByEventType = new HashMap<>();
    //方法key和方法所属的类组成的标识map
    final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();
    //产生方法key的builder
    final StringBuilder methodKeyBuilder = new StringBuilder(128);

        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;
        }
    
        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) {
                //没有添加,返回true
                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());
    
            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.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;
                }
            }
        }
    }```
    

    findUsingReflection:将订阅对象中所有打了标记的Subscribe的订阅方法,全部添加到findState的subscriberMethods中,然后通过getMethodsAndRelease,返回所有的订阅方法集合,并且将findState的对象放回对象池。
    查找方法集合后,返回EventBus执行注册的逻辑。

    synchronized (this) {
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    subscribe(subscriber, subscriberMethod);
                }
            }```
    subscribe:
    

    //添加到集合,并且按照优先级排序
    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;
    }
    }```
    这里用到有两个Cache:
    1、subscriptionsByEventType=EventType:Subscriptions(subscriber+subscriberMethod)
    2、typesBySubscriber=obj:EventTypes
    通过事件,快速定位到订阅者+订阅方法对象;通过订阅者,获取它所订阅的所有事件类型集合。
    粘性事件下一章再说。
    注册到些为止。

    unregister:通过typesBySubscriber获取所有注册的事件类型。然后通过subscriptionsByEventType获取每个事件类型对应该的订阅器集合,遍历每个订阅器,判断是否为当前对象,如果是,移除。

    post:先看PostingThreadState类用来说明当前执行的线程事件的执行状态。

    final static class PostingThreadState {
            final List<Object> eventQueue = new ArrayList<Object>();//为什么没有用实现队列的LinkedList呢?
            boolean isPosting;
            boolean isMainThread;
            Subscription subscription;
            Object event;
            boolean canceled;
        }```
    一个本地线程包装器,把PostingThreadState包装一下。
    

    private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
    @Override
    protected PostingThreadState initialValue() {
    return new PostingThreadState();
    }
    };```
    执行postSingleEvent里面有一个lookupAllEventTypes方法,获取事件参数对应的所有接口的类型。放到缓存eventTypesCache中。

    private static List<Class<?>> lookupAllEventTypes(Class<?> eventClass) {
            synchronized (eventTypesCache) {
                List<Class<?>> eventTypes = eventTypesCache.get(eventClass);
                if (eventTypes == null) {
                    eventTypes = new ArrayList<>();
                    Class<?> clazz = eventClass;
                    while (clazz != null) {
                        eventTypes.add(clazz);
                        addInterfaces(eventTypes, clazz.getInterfaces());//添加所有父类接口类型
                        clazz = clazz.getSuperclass();
                    }
                    eventTypesCache.put(eventClass, eventTypes);
                }
                return eventTypes;
            }
        }```
    接下来是postSingleEventForEventType具体的发送事件逻辑。
    

    if (eventInheritance) {
    List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
    int countTypes = eventTypes.size();
    for (int h = 0; h < countTypes; h++) {
    Class<?> clazz = eventTypes.get(h);
    subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
    }
    } else {
    subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }```
    里面的postToSubscription方法,根据订阅方法指定的线程模式,执行相应的逻辑。

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
            CopyOnWriteArrayList<Subscription> subscriptions;
            synchronized (this) {
                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;
        }
    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 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);
            }
        }```
    invokeSubscriber方法就是反射执行方法。
    
    执行过程:
    将要发送的对象:PendingPost,还有队列PendingPostQueue。
    mainThread对应的执行对象:HandlerPoster
    

    void enqueue(Subscription subscription, Object event) {
    //缓存获取发送对象
    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    synchronized (this) {
    //加入到执行队列里面
    queue.enqueue(pendingPost);
    //是否正在执行
    if (!handlerActive) {
    handlerActive = true;
    //发送主线程消息
    if (!sendMessage(obtainMessage())) {
    throw new EventBusException("Could not send handler message");
    }
    }
    }
    }

    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;//是否执行超时
        try {
            long started = SystemClock.uptimeMillis();
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }```
    

    BackgroundPoster:

    public void enqueue(Subscription subscription, Object event) {
            PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
            synchronized (this) {
                queue.enqueue(pendingPost);
                if (!executorRunning) {
                    executorRunning = true;
                    eventBus.getExecutorService().execute(this);
                }
            }
        }
    
        @Override
        public void run() {
            try {
                try {
                    while (true) {
                        PendingPost pendingPost = queue.poll(1000);
                        if (pendingPost == null) {
                            synchronized (this) {
                                // Check again, this time in synchronized
                                pendingPost = queue.poll();
                                if (pendingPost == null) {
                                    executorRunning = false;
                                    return;
                                }
                            }
                        }
                        eventBus.invokeSubscriber(pendingPost);
                    }
                } catch (InterruptedException e) {
                    Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
                }
            } finally {
                executorRunning = false;
            }
        }```
    
    AsyncPoster
    

    public void enqueue(Subscription subscription, Object event) {
    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
    queue.enqueue(pendingPost);
    eventBus.getExecutorService().execute(this);
    }@Override
    public void run() {
    PendingPost pendingPost = queue.poll();
    if(pendingPost == null) {
    throw new IllegalStateException("No pending post available");
    }
    eventBus.invokeSubscriber(pendingPost);
    }```
    这三个poster都是大同小异,获取执行队列。然后循环执行。

    接下分析一下粘性事件:事件A已经发送完毕,然后注册一个订阅A的粘性事件SB,那么立即还会向SB发送事件A。基于这个逻辑分析,那么粘性事件一定是在注册的时候。查看register的方法。

    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();
    //如果注册事件的类型在粘性事件的缓存里面执行checkPostStickyEventToSubscription
                        if (eventType.isAssignableFrom(candidateEventType)) {
                            Object stickyEvent = entry.getValue();
                            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                        }
                    }
                } else {
                    Object stickyEvent = stickyEvents.get(eventType);
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }```
    checkPostStickyEventToSubscription最终执行postToSubscription方法。
    stickyEvents是在那里添加的呢?EventBus并不是所有的事件都是粘性的,只有使用postSticky来发送的事件,才会被缓存下来。
    
    接下来分析(两个晚上,现在又到12:10分了,明天一定要弄完):索引的那部分逻辑,知识比较多。
    
    通过注解反身获取订阅对象的所有订阅方法,会消耗一定的性能,所以EventBus在编译期提供了生成代码的逻辑,把注解的方法,统一生成代码。运行期直接注册,就是我们将要分析的索引逻辑。
    里面有一些元数据的概念,用来描述对象的属性信息,各种info类,然后通过代码MyEventBusIndex类(build里面)。可以查看EventBusAnnotationProcessor代码生成逻辑。
    
    参考:
    http://www.cnblogs.com/all88/archive/2016/03/30/5338412.html
    http://www.jianshu.com/p/f057c460c77e
    http://kymjs.com/code/2015/12/12/01

    相关文章

      网友评论

          本文标题:事件总线-EventBus-源码学习过程

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