美文网首页Android面试相关Android开发Android知识
Eventbus3代码分析(七):整体结构

Eventbus3代码分析(七):整体结构

作者: dodo_lihao | 来源:发表于2016-10-10 00:43 被阅读176次

    整体结构

    自己没有怎么花时间画图,怕可能有遗漏的地方
    所以,先参考一下别人的代码分析
    (之前的内容,应该没有雷同的地方,参考别人的分析,也是自我提高的过程)
    我们先看一下下面的图:
    (来自 Trinea的分析:
    http://a.codekk.com/detail/Android/Trinea/EventBus%20%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90

    (这个图,虽然没有说明,但是我们通过例如 SubscriberMethodFinder的属性 还有图:)


    应该可以判断这个分析, 也就是
    上图是2.x的版本3.0和它还是有区别的我们暂时使用而已

    我们再贴一下对应2.4和3.0的类

    EventBus2.4 EventBus3.0

    类名上看,除了一个 我们分析过的 @interface Subscribe 注解类以外,其他类都是一致的
    (当然,我们简单看过SubscriberMethodFinder 类, 里面的实现 区别还是挺大的, 2.x的很好理解, 3.0的相对2.x,要复杂很多)


    简单说明

    来自 Trinea的上图,简单结构说明
    (只是结构,因为3.0 和 2.x 部分类的实现还是有很大区别的)
    我们结构按上图分析, 具体源码,根据实际情况,再做了解


    EventBus类简单关联

    从上图,我们可以知道,EventBus关联的类

    • SubscriberMethodFinder
    • Value为 CopyOnWriteArrayList<Subscription> 的Map
      • 这里 CopyOnWriteArrayList的List,是线程安全的
      • 我们看一下 CopyOnWriteArrayList类里面 add等方法都是 synchronized 的,我们可以知道是线程安全的,适合并发调用的情况
      • 对应的value的泛型是 Subcription,也就是说, 间接 关联 Subcription类
    • HandlerPoster
    • BackgroundPoster
    • AsyncPoster
    • EventBusBuilder

    其中

    • SubscriberMethodFinder ,
    • Subscription
      • 每次register后,都会通过SubscriberMethodFinder 去查找SubscriberMethod,在拼接为Subscription
      • 内部的SubscriberMethod引用在SubscriberMethodFinder 经常被使用
      • Subscription只是在 SubscriberMethod 外面包了一层,可以判断是否equal
      • 这个类2.x 和 3.0 也有区别。2.x有对应的优先级 priority 属性, 3.0没有
    • EventBusBuilder
      • EventBusBuilder 里面的线程池相关的ExecutorService对象,我们没有提过
      • 其实,也只是创建的默认的Executors.newCachedThreadPool(),
      • 具体也只是传递到EventBus中,最后被后面的XxxxPoster等类调用

    我们都大体分析过,剩下的,只有 **XxxxPoster 等类 **了


    XxxxPoster 在EventBus中的调用

    我们先看一下,对应的属性名称:

    • HandlerPoster mainThreadPoster
    • BackgroundPoster backgroundPoster
    • AsyncPoster asyncPoster

    我们对应的代码,无论是怎么调用,最终都会到
    postToSubscription方法

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

    我们前面分析注解的时候,知道
    对应的ThreadMode通过@Subscribe注解传入的,如果不传,默认为ThreadMode.POSTING
    上面大体有下面几种方式

    • invokeSubscriber(subscription, event);
    • mainThreadPoster.enqueue(subscription, event);
    • backgroundPoster.enqueue(subscription, event);
    • asyncPoster.enqueue(subscription, event);

    而invokeSubscriber方法,大体就是调用 Subscription 中 SubscriberMethod的Method反射,
    从而调用对应register类中的方法

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

    其他的3个xxxPoster

    其他的3个xxxPoster的enqueue(subscription, event) 方法
    就是调用封装类对应的enqueue(subscription, event)方法
    (个人感觉,这里都是调用相同的代码,写一个统一接口,可能会更方便一点)
    这里

    • BackgroundPoster 和 AsyncPoster 都是通过
      eventBus.getExecutorService().execute(this) 将当然这个Runnable加入线程池执行。
    • HandlerPoster 通过 Handler 去处理

    无论怎么样,最后,都会 EventBus的invokeSubscriber(pendingPost)去反射调用方法

    这里我们通过 Trinea 的类图,可以发现,
    最终都是关联 PendingPostQueue 实现的,
    而 PendingPostQueue 是关联 PendingPost 实现的

    • PendingPostQueue类
      • 只是一个简单的双向链表
      • 有2个PendingPost对象属性,head 和 tail,
      • enqueue方法,可以把对象对象赋值给类中的head 和 tail,还有head.next 和 tail.next
        • (如果tail == null, head != null, 会抛异常)
      • poll()方法, 释放对象。赋值 pendingPost 为 head 后,操作 head 和 tail,返回 pendingPost
      • poll(int maxMillisToWait)方法,head为null的时候,wait对应时间后,调用poll
    • PendingPost类
      • 有一个static List<PendingPost> 容器对象,在内存的 静态区 ,这样可以保证对应的唯一性
      • static 的 obtainPendingPost方法
        • 这里通过判断size,确定重新创建一个PendingPost对象,还是取出对象池中最后一个对象返回
      • static 的 releasePendingPost 方法
        • 在 EventBus中的 invokeSubscriber 方法, 在调用反射之前,会调用 PendingPost的releasePendingPost
        • releasePendingPost 方法,会将对象中的属性都设置为null,并且放入对象池中
        • (个人觉得, 这样也就节约了栈内存的消耗。既然只是为了节约栈内存的消耗,为什么要用双向链表?自己就不太明白了)

    大致流程

    这里,虽然一些写法,自己还不太清楚为什么
    只是简单理解和画一下自己的理解

    或者说, 可以更简单的实现,
    本来执行就是用线程池,为什么其他地方,还要写这么麻烦
    

    但是,大体还是很好理解的,图中左边,右边都是注册的Subscribe
    (当然,细节还有很多地方不理解,大体画了个图,如果有问题的地方,欢迎大家拍砖,本人会第一时间做修改)
    3种Poster提交

    HandlerPoster提交

    最后,再较大体的看一下调用过程
    (因为比较简单,自己就不画了,借用 Trinea 大神 的图)


    还有



    简单总结

    1. 之所以用起来比较简单, 是因为,调用端:注册,接收 和 发消息 可以解耦
    2. 通过EventBusBuilder初始化一些变量 和 线程池
    3. register通过 SubscriberMethodFinder 类 由 类名 和 注解,按key为类名 和 value为线程安全的CopyOnWriteArrayList存储
    4. 有的直接通过反射调用。有的通过 BackgroundPoster,AsyncPoster 或者 HandlerPoster 的方法,添加到 双向链表 中,再依次反射调用(具体见前面的分析)
    5. 最后,添加注解@Subscribe的地方,被反射调用,实现通知

    相关文章

      网友评论

        本文标题:Eventbus3代码分析(七):整体结构

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