美文网首页
EventBus 源码分析

EventBus 源码分析

作者: _SHYII | 来源:发表于2020-02-22 21:45 被阅读0次

    疑问:
    EventBus 注册,发送事件,注销时分别做了哪些操作?
    1、EventBus.getDefault().register(Object)、
    2、EventBus.getDefault().post(Object)
    3、EventBus.getDefault().unregister(Object)

    1、EventBus.getDefault().register(Object)
    步骤一

    首先通过 EventBus.getDefault() 获取 EventBus 单例

        //EventBus 单例对象
        static volatile EventBus defaultInstance;
        //默认 EventBusBuilder
        private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
        //获取单例 EventBus
        public static EventBus getDefault() {
            if (defaultInstance == null) {
                synchronized (EventBus.class) {
                    if (defaultInstance == null) {
                        defaultInstance = new EventBus();
                    }
                }
            }
            return defaultInstance;
        }
    
        public EventBus() {
            this(DEFAULT_BUILDER);
        }
        //初始默认值
        EventBus(EventBusBuilder builder) {
            subscriptionsByEventType = new HashMap<>();
            typesBySubscriber = new HashMap<>();
            stickyEvents = new ConcurrentHashMap<>();
            mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
            backgroundPoster = new BackgroundPoster(this);
            asyncPoster = new AsyncPoster(this);
            indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
            subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                    builder.strictMethodVerification, builder.ignoreGeneratedIndex);
            logSubscriberExceptions = builder.logSubscriberExceptions;
            logNoSubscriberMessages = builder.logNoSubscriberMessages;
            sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
            sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
            throwSubscriberException = builder.throwSubscriberException;
            eventInheritance = builder.eventInheritance;
            executorService = builder.executorService;
        }
    

    下面再看 register() 方法

        public void register(Object subscriber) {
            //1、获取注册对象的 class 对象 subscriberClass
            Class<?> subscriberClass = subscriber.getClass();
            //2、通过 class 对象 subscriberClass 找到该 class 的 SubscriberMethod 集合
            List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
            synchronized (this) {
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    //3、订阅注册对象支持注解 @Subscribe 的方法
                    subscribe(subscriber, subscriberMethod);
                }
            }
        }
    

    其中 SubscriberMethod 用来保存订阅方法的信息

    public class SubscriberMethod {
        //方法
        final Method method;
        //线程类型(ThreadMode.POST、ThreadMode.MAIN...)
        final ThreadMode threadMode;
        //事件类型,即发送的事件
        final Class<?> eventType;
        //优化级
        final int priority;
        //是否粘性事件
        final boolean sticky;
    }
    

    第二步找到注册对象中 @Subscribe 注解的方法列表,并将每个方法保存在 SubscriberMethod 中。第三步订阅注解的方法列表。下面先看第二步

    步骤二
    class SubscriberMethodFinder {
    
        List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
            //METHOD_CACHE 是一个 Map,用来缓存注册对象 Class 内所有的被@Subscribe注解的方法集合
            List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
            //优先从缓存中取
            if (subscriberMethods != null) {
                return subscriberMethods;
            }
            //ignoreGeneratedIndex 默认值为 false,
            if (ignoreGeneratedIndex) {
                subscriberMethods = findUsingReflection(subscriberClass);
            } else {
                //2.1、查找注册对象订阅方法列表
                subscriberMethods = findUsingInfo(subscriberClass);
            }
            if (subscriberMethods.isEmpty()) {
                throw new EventBusException("Subscriber " + subscriberClass
                        + " and its super classes have no public methods with the @Subscribe annotation");
            } else {
                //查找到的订阅方法加入到缓存中,key 为注册对象的 class 
                METHOD_CACHE.put(subscriberClass, subscriberMethods);
                return subscriberMethods;
            }
        }
    
        private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
            //初使化 FindState 对象
            FindState findState = prepareFindState();
            //给 findState.subscriberClass 赋值,关联注册对象
            findState.initForSubscriber(subscriberClass);
            while (findState.clazz != null) {
                //subscriberInfo 默认为空,高级用法暂不分析
                findState.subscriberInfo = getSubscriberInfo(findState);
                if (findState.subscriberInfo != null) {
                        ...
                    }
                } else {
                    //2.2 使用反射查找注册对象的订阅方法集合,存放在 findState 中
                    findUsingReflectionInSingleClass(findState);
                }
                //移到父类,继续 while 循环
                findState.moveToSuperclass();
            }
            //从 findState 中获取订阅方法集合,并释放 findState 对象
            return getMethodsAndRelease(findState);
        }
    
        //享元模式,降低创建 FindState 对象的数量,减小内存开销
        private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
        private FindState prepareFindState() {
            synchronized (FIND_STATE_POOL) {
                for (int i = 0; i < POOL_SIZE; i++) {
                    FindState state = FIND_STATE_POOL[i];
                    if (state != null) {
                        FIND_STATE_POOL[i] = null;
                        return state;
                    }
                }
            }
            return new FindState();
        }
        //重置 FindState 状态,并返回注册对象订阅的方法集合
        private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
            List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
            findState.recycle();
            synchronized (FIND_STATE_POOL) {
                for (int i = 0; i < POOL_SIZE; i++) {
                    if (FIND_STATE_POOL[i] == null) {
                        FIND_STATE_POOL[i] = findState;
                        break;
                    }
                }
            }
            return subscriberMethods;
        }
    }
    

    先具体看下 moveToSuperclass(),将 clazz 赋值给父类,所以也会去父类中查找订单事件,上面的 while 循环 clazz == null

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

    再去看 findUsingReflectionInSingleClass(),使用反射查找注册对象的订阅方法集合

        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) {
                //获取方法的修饰符(public、private)
                int modifiers = method.getModifiers();
                //方法的修饰符必须是 public
                if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                    //获取该方法入参集合
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    //入参只有一个
                    if (parameterTypes.length == 1) {
                        //获取被 @Subscribe 注解的方法
                        Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                        if (subscribeAnnotation != null) {
                            //获取参数类型
                            Class<?> eventType = parameterTypes[0];
                            if (findState.checkAdd(method, eventType)) {
                                //获取线程模型
                                ThreadMode threadMode = subscribeAnnotation.threadMode();
                                //方法名、参数、线程类型、粘性 信息存放在 SubscriberMethod 中,放加入到 subscriberMethods 集合中
                                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");
                }
            }
        }
    
    

    以上完成步骤 2 中对象注册对象的订阅方法集合,下面梳理一下:
    1、获取单例 EventBus 对象,并获取注册对象的 class 对象 subscriberClass
    2、获取注册对象的订阅方法集合 subscriberMethods,优先从缓存 METHOD_CACHE 中以 class 为 key 获取其 value ,获取不到再通过反射获取。
    3、获取不到时,初例化 FindState 对象,将 subscriberClass 赋值给 FindState.clazz
    4、反射获取 subscriberClass 的所有方法,遍历所有方法,将 public 修饰、只有一个参数且添加 Subscribe 注解的方法名,包装成 SubscriberMethod 对象并添加到 subscriberMethods 中。
    5、将 subscriberClass 的父类赋值给 FindState.clazz,获取父类的订阅方法,重复第 4 步,直到没有父类。
    6、重置 FindState 对象状态,返回注册对象的订阅方法集合 subscriberMethods

    步骤三

    正式注册订阅

    
        // Must be called in synchronized block
        private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
            //获取 event 类型
            Class<?> eventType = subscriberMethod.eventType;
            //将注册对象 subscriber 和 订阅方法 subscriberMethod 包装在 Subscription 中
            Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
            //获取 event 的订阅集合 subscriptions,可以理解成用来存放所有注册对象订阅过该 event 的方法
            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;
                }
            }
            //将 subscribedEvents 以 subscriber 为 key 添加到 typesBySubscriber 中即注册对象,unreigster 时会进行 remove
            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();
                        //如果 candidateEventType 是 eventType 的子类或者接口,发送粘性事件
                        if (eventType.isAssignableFrom(candidateEventType)) {
                            Object stickyEvent = entry.getValue();
                            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                        }
                    }
                } else {
                    Object stickyEvent = stickyEvents.get(eventType);
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        }
    

    以上则是注册对象的流程,下面看发送事件 post()

    2、EventBus.getDefault().post(Object)
        public void post(Object event) {
            //获取 PostingThreadState,currentPostingThreadState 是 ThreadLocal,可以当前线程的 PostingThreadState 对象
            PostingThreadState postingState = currentPostingThreadState.get();
            List<Object> eventQueue = postingState.eventQueue;
            //把 event 添加到事件集合中
            eventQueue.add(event);
    
            if (!postingState.isPosting) {
                postingState.isMainThread = Looper.getMainLooper() == Looper.myLooper();
                postingState.isPosting = true;
                if (postingState.canceled) {
                    throw new EventBusException("Internal error. Abort state was not reset");
                }
                try {
                    while (!eventQueue.isEmpty()) {
                        //1、当事件不为空时,发送消息
                        postSingleEvent(eventQueue.remove(0), postingState);
                    }
                } finally {
                    postingState.isPosting = false;
                    postingState.isMainThread = false;
                }
            }
        }
         //提供 PostingThreadState
        private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
            @Override
            protected PostingThreadState initialValue() {
                return new PostingThreadState();
            }
        };
    
        private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
            Class<?> eventClass = event.getClass();
            boolean subscriptionFound = false;
            //eventInheritance 默认为 true
            if (eventInheritance) {
                //查找 event 的所有 Class 对象,包括超类和接口,优先从缓存读取
                List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
                int countTypes = eventTypes.size();
                for (int h = 0; h < countTypes; h++) {
                    Class<?> clazz = eventTypes.get(h);
                    //2、发送事件
                    subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
                }
            } else 
            ...
        }
    
        private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
            CopyOnWriteArrayList<Subscription> subscriptions;
            synchronized (this) {
                //获取订阅过 event 的所有注册对象的所有订阅方法
                subscriptions = subscriptionsByEventType.get(eventClass);
            }
            if (subscriptions != null && !subscriptions.isEmpty()) {
                for (Subscription subscription : subscriptions) {
                        ...
                        //3、真正发送 event 事件
                        postToSubscription(subscription, event, postingState.isMainThread);
                        ...
                }
                return true;
            }
            return false;
        }
        //发送事件
        private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
            switch (subscription.subscriberMethod.threadMode) {
                //订阅的线程模式为当前线程
                case POSTING:
                    //4、执行订阅方法
                    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);
            }
        }
    
        void invokeSubscriber(Subscription subscription, Object event) {
            try {
                //反射执行该订阅方法!
                subscription.subscriberMethod.method.invoke(subscription.subscriber, event);
            } catch (InvocationTargetException e) {
                handleSubscriberException(subscription, event, e.getCause());
            } catch (IllegalAccessException e) {
                throw new IllegalStateException("Unexpected exception", e);
            }
        }
    

    第四步在主线程、后台线程执行用的是 Handler 、Thread 等实现原理较简单,最终调用订阅方式一样都是 invokeSubscriber,故不做分析。

    下面把 post() 流程梳理一下:
    1、获取当前线程对象,把 event 添加到 eventQueue 中,遍历 eventQueue 不为空时,发送消息。
    2、查找 event 的所有 Class 对象,包括超类和接口,优先从缓存读取,lookupAllEventTypes()。
    3、取订阅过 event 的所有注册对象的所有订阅方法,遍历一个个去发送事件。
    4、处理订阅线程模式,使用反射执行订阅方法。

    3、EventBus.getDefault().unregister(Object)

    unregister 比较简单,只移除注册即可

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

    知识点小结:
    1、EventBus 使用了享元模式,降低了内存中对象的数据。
    2、使用了线程安全的 CopyOnWriteArrayList 确保数据安全。
    3、使用 ThreadLocal 确保对象线程间共享。
    4、使用反射执行订阅方法


    参考:
    EventBus源码详解,看这一篇就够了

    相关文章

      网友评论

          本文标题:EventBus 源码分析

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