NO.5 EventBus 浅谈

零蚀


🔗 前言
🔗 Android 知识栈
🔗 Android 散装系列
🔗 NO.1 Handler->就这?
🔗 NO.2 Android 垃圾回收机制
🔗 NO.3 Android 测量、排版那点事
🔗 NO.4 项目无法一键打包?自己写个shell脚本吧


前言

  • 为什么看EventBus
    • 其实前几天并没有学习计划,这两天是比较放松的一天,大体任务都已经快要做完,现在的任务就是把TCP-IP的协议看完,然后看多线程,但是今天没有带书过来(也不想看电子书),所以今天就是空闲的一天,今天趁自己有点时间,来看看EventBus的内部构造。毕竟很多人多已经看过它如何实现,我怎么能错过。
  • 步骤
    • 这次不准备看使用方法了,我觉得轮子,不知道使用方法,就不知道也没什么大不了,使用时想知道,去看看文档好了,所以我觉得没有写案例的价值,与其把精力放在多方便(量变)上,不如多关注那些能(质变)事物,当然这样看源码大部分也算不上多有意义,大多只是敷衍一下社会需求。

EventBus源码

  • 注册相关
    • register方法
    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }
    
    • 我们可以看到这里有个findSubscriberMethods方法,这个方法作用和它的名字一样,它是通过你传入的类(Class)来查找你这个类中被订阅的方法。我们可以顺着这个代码继续向下看。
    for (Method method : methods) {
            int modifiers = method.getModifiers();
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                Class<?>[] parameterTypes = method.getParameterTypes();
                if (parameterTypes.length == 1) {
                    Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                    if (subscribeAnnotation != null) {
                        Class<?> eventType = parameterTypes[0];
                        if (findState.checkAdd(method, eventType)) {
                            ThreadMode threadMode = subscribeAnnotation.threadMode();
                            findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
                                    subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
                        }
                    }
                    .....
    
    • 我们可以看到,这里的他会在你这个subscriberClass中,通过反射,然后遍历这个类其中的所有的方法,看看有没有方法是被Subscribe的注解修饰过,当他找到后会将方法的信息参数保存在findState.subscriberMethods中,然后我们看看SubscriberMethod是什么,它其实里面就是一个方法的所有信息,在EventBus中所用到的信息,比如threadMode(线程),eventType(事件类型),priority(优先级),sticky(粘性)。看到这里,我们不难发现,我们常用的用于定义接受信息的方法设置,这里基本都有了。

    • 值得一提的是这里有一个methodString属性,而且注释明确写了不用Method的比较方法(equal),为什么不是使用方法(Method)自带的equal的比较方法,而是用String的equal(hashCode)方式来进行比较,其实跟着看了一下,这里主要的问题在于“性能”,如果是Method.equal可能要花费0.6秒左右的时间,这对手机来说绝对是不能容忍的。

    • 回到我们的register方法,然后就开始进入了subscribe,订阅主要是做什么的,他其实就是对eventType进行一些处理,他的处理逻辑如下。

    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;
            }
        }
    
        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();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }
    
    • 他会根据,你这个事件的优先级先排个序,然后再将这些事件分类,如class作为key,事件列表作为value保存在一个map中,最后对粘滞事件做出对应的处理,如果是粘滞事件,在获取到这个事件列表之后,会根据类别进行使用,这也就是粘滞事件异步操作的原理。
        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);
        }
    }
    

  • 发送消息
    • 发送消息
     /** Posts the given event to the event bus. */
    public void post(Object event) {
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        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()) {
                    postSingleEvent(eventQueue.remove(0), postingState);
                }
            } finally {
                postingState.isPosting = false;
                postingState.isMainThread = false;
            }
        }
    }
    
    • 其实到这里我们就可看出来,这里的post就是将消息加入了一个自己定义的list队列里面,然后如果队列不是空的,它就会使用postSingleEvent轮训的将消息发送出来。post方法就是这么简单。

    • 说了这么多,我们来看一下发送消息的逻辑,怎么发送消息的呢。我们可以先看看EventBus getDefault()

    /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }
    
    • 我们在使用EventBus.getDefault()时候这里创建了一个单例对象。然后这里构建了熟悉的属性,这些属性其实在之前的postToSubscription发送消息的方法里面进行了使用,这些属性其实就是一个Handler和一些Runnable,到这里你是不是心里就都明白了。

    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-HO0gYP11-1594795093699)(media/15946391187381/15947932716197.jpg)]

    • 他会根据具体的情况,来选择是用反射还是handler来发送消息,从而触发那些被订阅的方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

零蚀zero eclipse

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值