美文网首页
EventBus源码分析

EventBus源码分析

作者: loveCandyTQJ | 来源:发表于2018-05-15 15:35 被阅读0次
    EventBus github 地址
    在Android Studio中添加如下依赖:
    compile 'org.greenrobot:eventbus:3.1.1'
    

    以前在用EventBus之前,一直认为其原理 实现是观察者模式,经过本次分析才发现其原理是不正常的观察者模式,是使用反射加注解的方式实现的。本文章只介绍源码,然后自己手动手写一个类似的 功能。

    register源码解析
        public void register(Object subscriber) {
            //获取到注册对象,一般为MainActivity
            Class<?> subscriberClass = subscriber.getClass();
            //这里获取到解析此对象中有Subscribe注解信息列表封装成SubscriberMethod对象
            List<SubscriberMethod> subscriberMethods = 
            //此方法比较重要
            subscriberMethodFinder.findSubscriberMethods(subscriberClass);
            synchronized (this) {
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    subscribe(subscriber, subscriberMethod);
                }
            }
        }
    

    其中subscriberMethodFinder为:

        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                 builder.strictMethodVerification, builder.ignoreGeneratedIndex);
    

    其中eventBusBuilder为

        //默认的eventBusBuilder
        private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
    

    eventBusBuilder中变量值为,这些值会在下面分析中用到。

        boolean logSubscriberExceptions = true;
        boolean logNoSubscriberMessages = true;
        boolean sendSubscriberExceptionEvent = true;
        boolean sendNoSubscriberEvent = true;
        boolean throwSubscriberException;
        boolean eventInheritance = true;
        boolean ignoreGeneratedIndex;
        boolean strictMethodVerification;
        ExecutorService executorService = DEFAULT_EXECUTOR_SERVICE;
        List<Class<?>> skipMethodVerificationForClasses;
        List<SubscriberInfoIndex> subscriberInfoIndexes;
        Logger logger;
        MainThreadSupport mainThreadSupport;
    

    言归正传,我们回到findSubscriberMethods方法

        List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
            //从缓存中获取SubscriberMethod对象,第一次应该为空
            List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
            if (subscriberMethods != null) {
                return subscriberMethods;
            }
            //这里默认为false,可以查看builder中数据
            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;
            }
        }
    

    进入到findUsingInfo

        private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
            //享元模式获取对象
            FindState findState = prepareFindState();
            //将返回的对象重新赋值
            findState.initForSubscriber(subscriberClass);
            //当findState.clazz不为空时
            while (findState.clazz != null) {
                findState.subscriberInfo = getSubscriberInfo(findState);
                //因此不会走if
                if (findState.subscriberInfo != null) {
                    SubscriberMethod[] array = findState.subscriberInfo.getSubscriberMethods();
                    for (SubscriberMethod subscriberMethod : array) {
                        if (findState.checkAdd(subscriberMethod.method, subscriberMethod.eventType)) {
                            findState.subscriberMethods.add(subscriberMethod);
                        }
                    }
                } else {
                    //程序会走到这里
                    findUsingReflectionInSingleClass(findState);
                }
                findState.moveToSuperclass();
            }
            return getMethodsAndRelease(findState);
        }
    

    程序会走到findUsingReflectionInSingleClass

       private void findUsingReflectionInSingleClass(FindState findState) {
            Method[] methods;
            try {
                //获取到类(activity)中所有方法,不包含继承的方法
                methods = findState.clazz.getDeclaredMethods();
            } catch (Throwable th) {
                methods = findState.clazz.getMethods();
                findState.skipSuperClasses = true;
            }
            //遍历类中的方法
            for (Method method : methods) {
                //获取方法的类型
                int modifiers = method.getModifiers();
                //当方法为public时,这里就知道previte方法接收不到的原因了
                if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                    //获取到方法的参数数组,有可能会是多参
                    Class<?>[] parameterTypes = method.getParameterTypes();
                    //当方法参数为1时才会向下走,这里就知道为啥eventBus只能接收单个参数
                    if (parameterTypes.length == 1) {
                        //获取到方法上面的Subscribe注解
                        Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                        //如果注解不为空
                        if (subscribeAnnotation != null) {
                            //获取到参数的第一个类型(String.class)
                            Class<?> eventType = parameterTypes[0];
                            //检查数据中是否需要加入此方法和参数类型
                            if (findState.checkAdd(method, eventType)) {
                                //获取到方法上的threadMode
                                ThreadMode threadMode = subscribeAnnotation.threadMode();
                                //将method,eventType,threadMode,priority,sticky加入到集合中
                                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");
                }
            }
        }
    

    这时,我们便把当前类中需要的东西都封装成了SubscriberMethod对象。
    其中SubscriberMethod中字段意义为:

        public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
            //方法对象
            this.method = method;
            //方法上的threadMode
            this.threadMode = threadMode;
            //方法中参数类(String)
            this.eventType = eventType;
            //方法上priority,优先级
            this.priority = priority;
            //方法上sticky,粘性
            this.sticky = sticky;
        }
    

    进入getMethodsAndRelease方法,获取数据集合。

    private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
        //获取到当前subscriberMethods集合
       List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
        //清空findState对象中数据
        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;
                }
            }
        }
        //返回subscriberMethods
        return subscriberMethods;
    }
    

    至此findSubscriberMethods方法分析就完成了。可以理解为如下图:

    findSubscriberMethods.png
    注:图片引用自红橙Darren大神。懒得画了。哈哈哈!

    继续分析subscribe方法

    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
            //获取subscriberMethod中的参数类型
            Class<?> eventType = subscriberMethod.eventType;
            //根据主类(MAinActivity)和SubscriberMethod 创建Subscription 对象
            Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
            //从subscriptionsByEventType中获取Subscription list集合,第一次一般为空
            CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
            //当数据为空时,创建list,并且加入到subscriptionsByEventType中
            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);
                }
            }
            //获取到Subscription集合大小
            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;
                }
            }
            //通过类对象(MainActivity)获取到 方法参数(String)集合,第一次为空
            List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
            //创建新数组,并且把数据加入到typesBySubscriber
            if (subscribedEvents == null) {
                subscribedEvents = new ArrayList<>();
                typesBySubscriber.put(subscriber, subscribedEvents);
            }
            //将本方法参数对象加入到集合中
            subscribedEvents.add(eventType);
            //sticky分析省略
        }
    

    其中Subscription结构为:

        Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
            //主类Mactivity
            this.subscriber = subscriber;
            //类中对应的对象
            this.subscriberMethod = subscriberMethod;
            active = true;
        }
    

    其中用到的变量为:

    // subscriptionsByEventType 这个集合存放的是?
    // key 是 Event 参数的类
    // value 存放的是 Subscription 的集合列表
    // Subscription 包含两个属性,一个是 subscriber 订阅者(反射执行对象),
    // 一个是 SubscriberMethod 注解方法的所有属性参数值
    private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
    // typesBySubscriber 这个集合存放的是?
    // key 是所有的订阅者
    // value 是所有订阅者里面方法的参数的 class,eventType
    private final Map<Object, List<Class<?>>> typesBySubscriber;
    

    这一部分代码就是根据方法类型进行了分类,如图所示:

    • subscriptionsByEventType结构
      subscriptionsByEventType.png
    • typesBySubscriber 结构
      typesBySubscriber .png

    看到这里大家想说了,把这些东西存放到这些结构里面有什么用呢,为什么要这样做呢,那请大家带着这些疑问来看看我们下面讲的unregister

    unregister源码解析

    当我们再使用EventBus时候在某个类中注册了事件,当不需要接收事件时,我们应该解除注册,这样可以停止接收事件,也为了防止内存泄漏,优化应用。

    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 {
                logger.log(Level.WARNING, "Subscriber to unregister was not
                registered before: " + subscriber.getClass());
            }
        }
    

    这里就看到了,先从typesBySubscriber数据中获取参数列表

    unsubscribeByEventType方法

        private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
            //从subscriptionsByEventType中获取Subscription
            List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
            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;
                        subscriptions.remove(i);
                        i--;
                        size--;
                    }
                }
            }
        }
    

    然后根据参数列表从subscriptionsByEventType中获取List<Subscription>数据集,然后移除对应对象。
    至此EventBus的register和unregister就讲完了

    post源码解析
        public void post(Object event) {
            //获取到当前线程的postingState
            PostingThreadState postingState = currentPostingThreadState.get();
            //获取到当前线程的event事件
            List<Object> eventQueue = postingState.eventQueue;
            //将本event加入数组中
            eventQueue.add(event);
            //当不是posting状态
            if (!postingState.isPosting) {
                //当前是不是主线程
                postingState.isMainThread = isMainThread();
                //设置为posting状态
                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 {
                    postingState.isPosting = false;
                    postingState.isMainThread = false;
                }
            }
        }
    

    post数据时候,会先检查当前发送线程,然后获取到eventQueue事件队列,把数据加入到队列中,开始发送数据。

    postSingleEvent方法

        private void postSingleEvent(Object event, PostingThreadState postingState){
            //获取到传入参数的类型(String)
            Class<?> eventClass = event.getClass();
            boolean subscriptionFound = false;
            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);
            }
            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));
                }
            }
        }
    

    postSingleEventForEventType方法

        private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, 
            Class<?> eventClass) {
            CopyOnWriteArrayList<Subscription> subscriptions;
            synchronized (this) {
                //根据参数类型获取到Subscription集合
                subscriptions = subscriptionsByEventType.get(eventClass);
            }
            if (subscriptions != null && !subscriptions.isEmpty()) {
                //遍历Subscription集合
                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;
        }
    

    这个方法从subscriptionsByEventType数据结构中获取到当前需要通知的Subscription数组。

    postToSubscription方法,终于发送数据了。。。

        private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
            //根据mode选择执行方式
            switch (subscription.subscriberMethod.threadMode) {
                //在当前线程执行方法
                case POSTING:
                    invokeSubscriber(subscription, event);
                    break;
                //如果是主线程在当前线程执行,不是主线程,通过handler方式执行
                case MAIN:
                    if (isMainThread) {
                        invokeSubscriber(subscription, event);
                    } else {
                        mainThreadPoster.enqueue(subscription, event);
                    }
                    break;
                 //如果主线程订阅了则在主线程中执行,否则在当前线程
                case MAIN_ORDERED:
                    if (mainThreadPoster != null) {
                        mainThreadPoster.enqueue(subscription, event);
                    } else {
                        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);
            }
        }
    

    invokeSubscriber方法

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

    通过反射,执行了方法。

    到此为止post的分析也完成了。感兴趣的可以去看看如何发送到主线程的,其原理也是handler,有空再补上。

    自己手写实现github地址

    相关文章

      网友评论

          本文标题:EventBus源码分析

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