深入EventBus 事件总线的框架源码学习

Code 代码
2020年2月9日 ~

在看源码之前,需要掌握的主要知识点:集合、反射、注解。
框架基本上是用这三方面的知识点写的,没掌握的最好去掌握下,不然看的时候会晕头转向。

一、注册源码解析

注册的一系列流程,其流程图(来自网络)如下:

这里写图片描述

我们在使用EventBus的时候,首先做的第一件事就是给事件注册对象了,通俗来讲就是说要接收消息,需要登记信息,方便有消息可以通知到你。
     那么EventBus是如何注册信息的呢?又是如何接收事件?
我们带着疑问看代码,效果会更好。
注册订阅者代码:

	//将当前对象进行注册,表示这个对象要接收事件
	EventBus.getDefault().register(this);

注册源码:

    public void register(Object subscriber) {
	    //获取订阅者的Class类型
        Class<?> subscriberClass = subscriber.getClass();
        //根据订阅者的Class类型,获取订阅者的订阅方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

List< SubscriberMethod > subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
这句代码表示的是:通过订阅者的Class类型获取订阅者的所有的订阅方法。那它是如何获取所有的订阅方法的呢?

我们再看一下findSubscriberMethods方法的源码

 List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
 //先从缓存中查找是否存在订阅方法
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
 //是否忽略注解器生成的MyEventBusIndex类
        if (ignoreGeneratedIndex) {
  //利用反射来获取订阅类中的订阅方法信息      
            subscriberMethods = findUsingReflection(subscriberClass);
        } else {
  //从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息     
            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;
        }
    }

上面的源码在查找订阅方法信息是用了两种方式,如下所示:

 if (ignoreGeneratedIndex) {
	 //利用反射来获取订阅类中的订阅方法信息      
	            subscriberMethods = findUsingReflection(subscriberClass);
	        } else {
	  //从注解器生成的MyEventBusIndex类中获得订阅类的订阅方法信息     
	            subscriberMethods = findUsingInfo(subscriberClass);
	        }

ignoreGeneratedIndex的判断是看你的build配置文件是否配置相关注解处理器信息如下:

这个方法的大致逻辑是这样:
    先从缓存中查找订阅方法信息,如果没有就利用反射或注解来获取订阅方法信息。

1、使用注解处理器
findUsingInfo(Class< ? > subscriberClass)

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

EventBus提供了一个EventBusAnnotationProcessor注解处理器来在编译期通过读取@Subscribe()注解并解析,
处理其中所包含的信息,然后生成java类来保存所有订阅者关于订阅的信息,这样就比在运行时使用反射来获得这些订阅者的
信息速度要快。
EventBus 3.0使用的是编译时注解,而不是运行时注解。通过索引的方式去生成回调方法表,通过表可以看出,极大的提高了性能。

2、通过反射获取的订阅方法信息

findUsingReflection(subscriberClass)源码

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
     while (findState.clazz != null) {
          //通过发射获得订阅方法信息
          findUsingReflectionInSingleClass(findState);
            //查找父类的订阅方法信息
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

FindState是一个实体类,用来保存订阅者和订阅方法的信息,以及校验订阅方法。写了那么多,其实最终是调用findUsingReflectionInSingleClass(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) {
            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");
            }
        }
    }

开始订阅事件的源码:
订阅者有了,订阅方法也有了。接下来是当做参数进行订阅,

  // Must be called in synchronized block
    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) {
                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);
            }
        }
    }

注册只有一句代码,但是深入里面去,却是做了许许多多的工作。
其实,做了那么多的工作,无非就是存储订阅者的相关信息(订阅者、订阅方法、事件对象等),为后面的事件分发做的铺垫。

订阅逻辑:

	1. 首先调用register()注册订阅对象。
	2. 根据订阅对象获取该订阅对象的所有订阅方法。
	3.   subscriptionsByEventType.put(eventType, subscriptions),根据该订阅者的所有订阅的事件类型,将订阅者存入到每个以 事件类型为key, 以订阅者信息(subscriptions)为values的map集合中。
	4.  typesBySubscriber.put(subscriber, subscribedEvents),然后将订阅事件添加到以订阅者为key ,以订阅者所有订阅事件为values的map集合中.  

二、事件分发解析

事件分发的流程图(来源网络)

这里写图片描述

注册订阅者是为了后面的事件分发,以便知道该将事件发送给谁,而事件的接收就是订阅者的订阅方法。
事件分发代码:

	EventBus.getDefault().post(new Event());

看post方法的源码:
参数即要发送的事件对象

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

PostingThreadState 是EventBust的静态内部类,它保存当前线程的事件队列和线程状态。

final static class PostingThreadState {
        final List<Object> eventQueue = new ArrayList<Object>();//当前线程的事件队列
         boolean isPosting;//是否有事件正在分发
         boolean isMainThread;//post的线程是否是主线程
         Subscription subscription;//订阅者
         Object event;//订阅事件
         boolean canceled;//是否取消
     }

参数一:事件对象
参数二:发送状态
postSingleEvent(eventQueue.remove(0), postingState)执行源码

  private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
	  //获取事件对象的Class类型
        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) {
                Log.d(TAG, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

postSingleEventForEventType(event, postingState, eventClass)
看了那么多的源码才发现这个方法才是罪魁祸首。最终发射事件的方法。
那好接着看看他的源码:

  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(subscription, event, postingState.isMainThread);
开始处理订阅者的信息

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

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

事件分发逻辑:

1. 获取事件队列。
2. 循环取出队列中的事件。
3. 获取订阅者集合,然后遍历,最后通过反射调用订阅者的订阅方法。

三、取消注册解析

 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());
        }
    }
 private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {
 //根据事件类型获取事件类型的所有订阅者
        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--;
                }
            }
        }
    }

取消注册逻辑:

1、首先根据订阅者获取所有订阅事件。
2、遍历订阅事件集合。
3、根据订阅事件获取订阅该事件的订阅者集合。
4、遍历订阅者集合,然后根据传入的订阅者做比较,判断是否是同一订阅者。如果是则移除,反之。

四、post和postSticky的区别

    /** 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;
            }
        }
    }
   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);
    }
从上面的比较来看postSticky利用 Map<Class<?>, Object> 数据结构来存储sticky事件,再调用post方法。接下去就是等待时机触发
了,这个时机就是等待注册的那个时候,然后标有sticky标记的方法就好被触发执行。
在EventBus类中有一个subscribe方法里面有如下的一段代码,这段主要是判断是否是黏性事件,如果是的话就执行,不是的话直接跳过。
 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);
            }
        }

其实post和postSticky的区别用通俗的话来讲就是post要先注册,然后立刻开始处理事件对象。而postSticky就是不管你有没有注册,先发送事件对象再说,然后存储起来,直到有对象来注册这个sticky事件。

五、其它类分析

订阅方法类:主要用来存储订阅方法的相关信息。

//有方法、线程模型、事件类型、优先级、粘性等属性。
public class SubscriberMethod {
    final Method method;
    final ThreadMode threadMode;
    final Class<?> eventType;
    final int priority;
    final boolean sticky;
    /** Used for efficient comparison */
    String methodString;
}

订阅者信息类,用来存储订阅者和订阅方法。

final class Subscription {
    final Object subscriber;
    final SubscriberMethod subscriberMethod;
    /**
     * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
     * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
     */
    volatile boolean active;
}

EventBus的事件处理函数通常需要指定处理线程,EventBus提供了四种线程模型POSTING(默认)、MAIN、BACKGROUND、ASYNC

public enum ThreadMode {
  //POSTING表示如果使用事件处理函数指定了线程模型为PostThread,那么该事件在哪个线程发布出来的,事件处理函数就会在这个线程中运行,也就是说发布事件和接收事件在同一个线程。在线程模型为PostThread的事件处理函数中尽量避免执行耗时操作,因为它会阻塞事件的传递,甚至有可能会引起ANR。
    POSTING,
    
//如果使用事件处理函数指定了线程模型为MainThread,那么不论事件是在哪个线程中发布出来的,该事件处理函数都会在UI线程中执行。该方法可以用来更新UI,但是不能处理耗时操作。
    MAIN,

//如果使用事件处理函数指定了线程模型为BackgroundThread,那么如果事件是在UI线程中发布出来的,那么该事件处理函数就会在新的线程中运行,如果事件本来就是子线程中发布出来的,那么该事件处理函数直接在发布事件的线程中执行。在此事件处理函数中禁止进行UI更新操作
    BACKGROUND,

  //如果使用事件处理函数指定了线程模型为Async,那么无论事件在哪个线程发布,该事件处理函数都会在新建的子线程中执行。同样,此事件处理函数中禁止进行UI更新操作
    ASYNC
}

标签

Great! You've successfully subscribed.
Great! Next, complete checkout for full access.
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.