eventbus3.1.1源码分析

文章目录

    • 使用
      • gradle引入
      • 注册订阅者、解除订阅者,订阅方法
      • 发送事件
    • 问题?
    • 源码解读
      • register源码解读
      • post源码解读
      • unRegister源码解读
    • 总结
      • 注册逻辑
      • 发送逻辑
      • 解除注册逻辑

使用

gradle引入

implementation 'org.greenrobot:eventbus:3.1.1'

注册订阅者、解除订阅者,订阅方法

    //01
    EventBus.getDefault().register(this);
    //02
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void reFreshDetail(TestBean testBean) {
        if(testBean.isUpdate()){
            Toast.makeText(this, "555666", Toast.LENGTH_SHORT).show();
        }
    }
    //03
    EventBus.getDefault().unregister(this);

发送事件

 TestBean testBean = new TestBean();
 testBean.setUpdate(true);
 EventBus.getDefault().post(testBean);

问题?

EventBus如何将消息注册者和消息接收这绑定起来达到准确的分发?EventBus通过post发送完事件后,在订阅者里面为什么可以接受到,并能执行相应的方法?

源码解读

其实就是原理分析。Eventbus源码分析其实主要从三个方法入手,register、post、unregister。首先EventBus.getDefault().register(this)进入源码,getDefault源码如下,一个标准的dcl单例。

  public static EventBus getDefault() {
      if (defaultInstance == null) {
          synchronized (EventBus.class) {
              if (defaultInstance == null) {
                  defaultInstance = new EventBus();
              }
          }
      }
      return defaultInstance;
  }

register源码解读

  public void register(Object subscriber) {
      Class<?> subscriberClass = subscriber.getClass();
  //01
      List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
      synchronized (this) {
          for (SubscriberMethod subscriberMethod : subscriberMethods) {
  //02
              subscribe(subscriber, subscriberMethod);
          }
      }
  }

register01通过字面意思就是根据注册者这个类,获取该注册者所有的订阅方法。具体怎么实现的,需要看findSubscriberMethods方法。

     List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }

        if (ignoreGeneratedIndex) {
     //01
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
     //02
            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;
        }
    }

核心方法就是通过调用findSubscriberMethods01中findUsingReflection和findSubscriberMethods02中的findUsingInfo方法获取订阅方法,然后放入一个METHOD_CACHE 的map中(以订阅者这个类为key,订阅方法为value)方便之后从map中获取订阅方法。

     private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

    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) {
            int modifiers = method.getModifiers();
            //方法的标识符必须是public 
            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()));
                        }
                    }
                } 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");
            }
        }
    }

跟踪findSubscriberMethods01中findUsingReflection方法发现最后是通过根据类的反射获取有subscribe注解的方法。

     private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findState.subscriberInfo = getSubscriberInfo(findState);
            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);
    }

跟踪findSubscriberMethods02方法,findUsingInfo最后依旧调用findUsingReflectionInSingleClass方法。

我们接着开register02其实是遍历该注册者的所有订阅方法,然后调用subscribe方法。比较重要,源码如下:

     // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class<?> eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    //01
        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;
            }
        }

    //02
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);
    //03
        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).
                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);
            }
        }
    }

subscribe01目的,主要是生成一个subscriptionsByEventType的map,以订阅事件类型为key,以Subscription对象为value,Subscription即以订阅者和订阅方法封装的新对象。subscribe02目的,主要是生成一个typesBySubscriber的map,以订阅者为key,订阅事件类型为value。请记住这两个map很重要。subscribe03主要是判断如果事件是粘性事件的话单独处理,调用checkPostStickyEventToSubscription方法。

      private void checkPostStickyEventToSubscription(Subscription newSubscription, Object stickyEvent) {
        if (stickyEvent != null) {
            // If the subscriber is trying to abort the event, it will fail (event is not tracked in posting state)
            // --> Strange corner case, which we don't take care of here.
            postToSubscription(newSubscription, stickyEvent, isMainThread());
        }
    }

checkPostStickyEventToSubscription里面最后会调用postToSubscription方法,最后通过反射,调用订阅者的订阅方法。下面post流程最后也会调用,具体下面分析。

post源码解读

     public void post(Object event) {
        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;
            }
        }
    }

首先通过currentPostingThreadState获取PostingThreadState对象。while循环eventQueue队列,如果不为空就去调用postSingleEvent方法,直到队列取完。

     private final ThreadLocal<PostingThreadState> currentPostingThreadState = new ThreadLocal<PostingThreadState>() {
        @Override
        protected PostingThreadState initialValue() {
            return new PostingThreadState();
        }
    };

currentPostingThreadState其实就是一个包裹PostingThreadState 的线程内部存储类ThreadLocal。

    //PostingThreadState
     final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<>();
        boolean isPosting;
        boolean isMainThread;
        Subscription subscription;
        Object event;
        boolean canceled;
    }

PostingThreadState本地封装的一个实体

     private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        if (eventInheritance) {
    //01
            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 {
    //02
            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) {
    //03
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

首先eventInheritance变量它表示一个子类事件能否响应父类的onEvent() 方法。根据postSingleEvent01,通过lookupAllEventTypes获取将一个类的父类,接口,父类的接口,父类接口的父类,全部添加到全局静态变量 eventTypes 集合中。然后遍历调用postSingleEventForEventType方法,postSingleEvent02也是调用postSingleEventForEventType方法。postSingleEvent03则是发送一个没有订阅者的NoSubscriberEvent。

    private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            subscriptions = subscriptionsByEventType.get(eventClass);
        }
        if (subscriptions != null && !subscriptions.isEmpty()) {
            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;
    }

跟踪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 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);
        }
    }
对声明不同线程模式的事件做不同的响应方法,继续跟踪invokeSubscriber方法

     void invokeSubscriber(PendingPost pendingPost) {
        Object event = pendingPost.event;
        Subscription subscription = pendingPost.subscription;
        PendingPost.releasePendingPost(pendingPost);
        if (subscription.active) {
            invokeSubscriber(subscription, event);
        }
    }

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

最终还是调用 subscription.subscriberMethod.method.invoke(subscription.subscriber, event);根据invoke方法传入类,和参数类型,调用订阅者中onEvent方法。

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(),从这个事件的所有订阅者集合中将要取消注册的订阅者移除。最后再以:当前订阅者为 key 全部订阅事件集合为 value 的一个 Map 的 Entry 移除,完成取消注册的全部过程。

总结

注册逻辑

rigister注册一个订阅者;
根据反射获取该订阅者的所有订阅方法;
订阅者和订阅方法封装为Subscription,根据该订阅者所有的订阅事件类型,
然后将订阅事件类型为key,Subscription为values放到一个subscriptionsByEventType;
然后将订阅事件放到以 订阅者为key,该订阅者所有的订阅事件为values放到typesBySubscriber;

发送逻辑

获得当前线程事件队列;
将要发送的事件放到事件队列中;
根据事件类型获取所有的订阅者;
在相应线程根据反射获取订阅方法;

解除注册逻辑

获取订阅者的所有订阅的事件类型
从事件类型的订阅者集合中移除订阅者

先根据事件类型获取所有subscriptionsByEventType注册的订阅者和订阅方法
找出要注销的订阅者,移除该订阅者中的所有订阅方法。

你可能感兴趣的:(Android框架篇,Android源码分析)