美文网首页
EventBus 3.0解析

EventBus 3.0解析

作者: 大玩具 | 来源:发表于2018-08-14 19:33 被阅读23次

    以下是基于3.0的代码进行的
    git仓库:https://github.com/greenrobot/EventBus.git


    简介

    简单来说,EventBus是用在Activity,Service,Fragment以及Thread之间的一个事件总线框架,用来在他们之间传递消息。

    使用

    下面简述一下用法。

    1. module级别的gradle中添加依赖 compile'org.greenrobot:eventbus:3.0.0'
    2. 拿Activity为例,在onCreate中添加注册代码 EventBus.getDefault().register(this),同时在onDestory中添加注销代码EventBus.getDefault().unregister(this)
      3.在当前事件的订阅者中添加Event方法,方法内部参数为你的事件类型。
      4.在事件发送的class里面通过post(事件类型)来传达你的信息

    解析

    还是带着问题来看代码吧,这样到最后至少给自己一个交代:理解了什么。
    其实要去看源码的时候,大都是会用这样一个东西了,那我就会想,如果要我自己去实现这个bus我会怎么做。嗯,
    a. 得有个东西收集我的订阅的事情吧,然后当有人发布事件的时候,还能通知我;
    b. 也得有个方法,当我被销毁的时候,事件是不是也得被移除,不删除的话必然npe了;
    c. 粘性事件
    d. 事件分发的原理

    注册过程

      public void register(Object subscriber) {
            //获取订阅者的类名
            Class<?> subscriberClass = subscriber.getClass();
            // 根据类名去查找他订阅的方法  SubscriberMethod里面包含订阅者的类名,方法的优先级,线程以及方法
            List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
            synchronized (this) {
                //遍历当前类的所有订阅方法,把他们放进list里面
                for (SubscriberMethod subscriberMethod : subscriberMethods) {
                    subscribe(subscriber, subscriberMethod);
                }
            }
        }
    
    

    // 下面是订阅方法

    
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        //将subscriber和subscriberMethod封装成 Subscription
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //根据事件类型获取特定的 Subscription
        CopyOnWriteArrayList<Subscription> subscriptions = subscriptionsByEventType.get(eventType);
        //如果为null,说明该subscriber尚未注册该事件
        if (subscriptions == null) {
            subscriptions = new CopyOnWriteArrayList<>();
            subscriptionsByEventType.put(eventType, subscriptions);
        } else {
            //如果不为null,并且包含了这个subscription 那么说明该subscriber已经注册了该事件,抛出异常
            if (subscriptions.contains(newSubscription)) {
                throw new EventBusException("Subscriber " + subscriber.getClass() + " already registered to event "
                        + eventType);
            }
        }
    
        //根据优先级来设置放进subscriptions的位置,优先级高的会先被通知
        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;
            }
        }
    
        //根据subscriber(订阅者)来获取它的所有订阅事件
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            //把订阅者、事件放进typesBySubscriber这个Map中
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
    
        //下面是对粘性事件的处理
        if (subscriberMethod.sticky) {
            //从EventBusBuilder可知,eventInheritance默认为true.
            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 {
                //根据eventType,从stickyEvents列表中获取特定的事件
                Object stickyEvent = stickyEvents.get(eventType);
                //分发事件
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }
    

    首先,他先去自己家里面找,看一下这个对象,准确的说应该是这个类,有没有在EventBus里面注册过如果注册过就直接拿出保存method的list,否则就建立个list,通过注解信息(findUsingReflection),或者(findUsingInfo)两个方法来拿到注册的方法。然后以eventType(类名)作为key,将他们存起来。

    粘性事件(stickyEvent)

    粘性事件与一般的事件不同,粘性事件是先发送出去,然后让后面注册的订阅者能够收到该事件.
    事件发送的时候是通过postSticky方法发送的,然后把事件放到stickyEvents这个map里面去,和原来的区分开,最后调用post方法。

    public void postSticky(Object event) {
         synchronized (stickyEvents) {
            stickyEvents.put(event.getClass(), event);
        }
        // Should be posted after it is putted, in case the subscriber wants to remove immediately
        post(event);
    }
    

    那么为什么当注册订阅者的时候可以马上接收到匹配的事件呢。这是由于在subscribe方法中,我们都会便利一遍所有的粘性事件,然后调用checkPostStickyEventToSubscription方法进行分发。

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

    结合注册过程,注销比较容易理解。我注册的时候不是有两个集合放订阅方法和订阅者吗,注销的时候我就从typesBySubscriber里面拿到当前subscriber订阅的所有方法,让subscriptionsByEventType去删除,然后再把这个订阅者拿掉。

    事件如何调用

     /** Posts the given event to the event bus. */
       public void post(Object event) {
        //获取一个postingState
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        //将事件加入队列中
        eventQueue.add(event);
        if (!postingState.isPosting) {
        //判断当前线程是否是主线程
                postingState.isMainThread = isMainThread();
                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;
            }
        }
    }
    
    private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        //eventInheritance  事件继承。EventBus会考虑事件的继承树
        //如果事件继承自父类,那么父类也会作为事件被发送
        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) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }
    
    //经过一系列操作之后 来到最终的分发方法
     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 MAIN_ORDERED:
                    if (mainThreadPoster != null) {
                        mainThreadPoster.enqueue(subscription, event);
                    } else {
                        // temporary: technically not correct as poster not decoupled from subscriber
                        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);
            }
        }
        //通过反射来调用事件
          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);
            }
        }
    

    事件发送代码比较清晰,就不细讲了。

    总结

    EventBus的工作原理,主要分四个方面,注册注销,事件分发与消化。

    EventBus里面有两个map,一个subscriptionsByEventType的key是订阅方法(eventType:onEvent(EventType e)),value是包含key下面的订阅方法对象(Subscription);
    另一个map(typesBySubscriber),key是订阅者类名(subscriber),value是订阅的事件类型(eventType)。另一个map(typesBySubscriber)以订阅者类名为key,订阅者的eventTypes为value,刚好能串起两兄弟。

    • 注册 注册的时候就抽出Subscriber里面的订阅方法,根据方法的优先级,是否是粘性事件等信息,包装成一个subscription,分别存到上述两个容器中。
    • 注销 注册注销传进来的都是类对象,注销的时候根据类对象的className,去typesBySubscriber里面找对应的eventTypes(list),然后遍历list的value,以value为key,去subscriptionsByEventType
      中迭代拿掉注销的内容。
    • 事件发送 post的时候,先去找eventType的父类以及接口,然后把所有的事件发送出去,牵扯到线程切换一类的都由封装的一个poster处理。
    • 事件接收 接收就很简单了,subscriber拿得到,方法也拿得到,直接去调用就好了。

    为什么会有两个呢,内容好像都差不多:你想啊,你发送事件的时候,发的是事件(eventType)吧,如果只有一个容器,你是不是还得遍历类名,然后遍历类中的方法去调用。两个容器刚好根据功能区分开,一个用在注册的时候,另一个用在查状态以及注销的时候,你注销不是传的类名吗,我就去typesBySubscriber里面拿到你的信息,然后根据subscriptionsByEventType,去里面剔除掉你,效率也提高了,也容易理解了。

    结语

    以上是对EventbUs3.0的简单解析,欢迎勘误

    相关文章

      网友评论

          本文标题:EventBus 3.0解析

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