EventBus 3.0进阶:源码及其设计模式 完全解析

来源:互联网 发布:ubuntu 16.04 pyqt5 编辑:程序博客网 时间:2024/05/23 00:10

EventBus 3.0进阶:源码及其设计模式 完全解析

前言

在上一篇文章:EventBus 3.0初探: 入门使用及其使用 完全解析中,笔者为大家介绍了EventBus 3.0的用法,相信大家对其的使用也比较熟悉了。我们学习使用一个开源库,不但要知道其怎么使用,也要对其的实现原理有一定的熟悉,学习并借鉴它优秀的实现思想,这样对我们以后的开发又或者是自己的开源项目都有很大的意义。那么今天的文章,就是EventBus 3.0的进阶,剖析它的实现原理以及对其使用的设计模式进行解析。

本文导读

由于EventBus较为复杂,因此本文也相当长,所以本文分为以下几个部分:创建、注册、发送事件、关于粘性事件的解析、以及最后的思考。读者可以有选择性地选取某部分来进行阅读。

实现原理

创建

上一篇文章提到,要想注册成为订阅者,必须在一个类中调用如下:

EventBus.getDefault().register(this);

那么,我们看一下getDefault()的源码是怎样的,EventBus#getDefault()

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

可以看出,这里使用了单例模式,而且是双重校验的单例,确保在不同线程中也只存在一个EvenBus的实例。

单例模式:一个类有且仅有一个实例,并且自行实例化向整个系统提供。

然而,我们看看EventBus的构造方法:

/**   * Creates a new EventBus instance; each instance is a separate scope in which events are delivered. To use a   * central bus, consider {@link #getDefault()}.  */public EventBus() {    this(DEFAULT_BUILDER);}

它的构造方法并没有设置成私有的!这是为什么?从注解我们看到,每一个EventBus都是独立地、处理它们自己的事件,因此可以存在多个EventBus,而通过getDefault()方法获取的实例,则是它已经帮我们构建好的EventBus,是单例,无论在什么时候通过这个方法获取的实例都是同一个实例。除此之外,我们可以通过建造者帮我们建造具有不同功能的EventBus。
我们继续看上面的this(DEFAULT_BUILDER)调用了另一个构造方法:

  EventBus(EventBusBuilder builder) {    subscriptionsByEventType = new HashMap<>();    typesBySubscriber = new HashMap<>();    stickyEvents = new ConcurrentHashMap<>();    mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);    backgroundPoster = new BackgroundPoster(this);    asyncPoster = new AsyncPoster(this);    //一系列的builder赋值}

可以看出,对成员变量进行了一系列的初始化,那么我们来看看几个关键的成员变量:

private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;private final Map<Object, List<Class<?>>> typesBySubscriber;private final Map<Class<?>, Object> stickyEvents;

subscriptionsByEventType:以event(即事件类)为key,以订阅列表(Subscription)为value,事件发送之后,在这里寻找订阅者,而Subscription又是一个CopyOnWriteArrayList,这是一个线程安全的容器。你们看会好奇,Subscription到底是什么,其实看下去就会了解的,现在先提前说下:Subscription是一个封装类,封装了订阅者、订阅方法这两个类。
typesBySubscriber:以订阅者类为key,以event事件类为value,在进行register或unregister操作的时候,会操作这个map。
stickyEvents:保存的是粘性事件,粘性事件上一篇文章有详细描述。
回到EventBus的构造方法,接下来实例化了三个Poster,分别是mainThreadPoster、backgroundPoster、asyncPoster等,这三个Poster是用来处理粘性事件的,我们下面会展开讲述。接着,就是对builder的一系列赋值了,这里使用了建造者模式

建造者模式:将一个复杂对象的构造与它的表示分离,使同样的构建过程可以创建不同的表示。

这里的建造者是EventBusBuilder,它的一系列方法用于配置EventBus的属性,使用getDefault()方法获取的实例,会有着默认的配置,上面说过,EventBus的构造方法是公有的,所以我们可以通过给EventBusBuilder设置不同的属性,进而获取有着不同功能的EventBus。那么我们来列举几个常用的属性加以讲解:

//默认地,EventBus会考虑事件的超类,即事件如果继承自超类,那么该超类也会作为事件发送给订阅者。//如果设置为false,则EventBus只会考虑事件类本身。boolean eventInheritance = true;public EventBusBuilder eventInheritance(boolean eventInheritance) {    this.eventInheritance = eventInheritance;    return this;}//当订阅方法是以onEvent开头的时候,可以调用该方法来跳过方法名字的验证,订阅这类会保存在List中List<Class<?>> skipMethodVerificationForClasses;public EventBusBuilder skipMethodVerificationFor(Class<?> clazz) {    if (skipMethodVerificationForClasses == null) {        skipMethodVerificationForClasses = new ArrayList<>();    }    skipMethodVerificationForClasses.add(clazz);    return this;}//更多的属性配置请参考源码,均有注释//...

那么,我们通过建造者模式来手动创建一个EventBus,而不是使用getDefault()方法:

EventBus eventBus = EventBus.builder()        .eventInheritance(false)        .sendNoSubscriberEvent(true)        .skipMethodVerificationFor(MainActivity.class)        .build();

注册

好了,以上说了一大推关于EventBus的创建,接下来,我们继续讲它的注册过程。要想使一个类成为订阅者,那么这个类必须有一个订阅方法,以@Subscribe注解标记的方法,接着调用register()方法来进行注册。那么我们直接来看EventBus#register()

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

先获取了订阅者类的class,接着交给SubscriberMethodFinder.findSubscriberMethods()处理,返回结果保存在List<SubscriberMethod>中,由此可推测通过上面的方法把订阅方法找出来了,并保存在集合中,那么我们直接看这个方法,SubscriberMethodFinder#findSubscriberMethods()

findSubscriberMethods

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {    //首先从缓存中取出subscriberMethodss,如果有则直接返回该已取得的方法    List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);    if (subscriberMethods != null) {        return subscriberMethods;    }    //从EventBusBuilder可知,ignoreGenerateIndex一般为false    if (ignoreGeneratedIndex) {        subscriberMethods = findUsingReflection(subscriberClass);    } else {        subscriberMethods = findUsingInfo(subscriberClass);    }    if (subscriberMethods.isEmpty()) {        throw new EventBusException("Subscriber " + subscriberClass                + " and its super classes have no public methods with the @Subscribe annotation");    } else {        //将获取的subscriberMeyhods放入缓存中        METHOD_CACHE.put(subscriberClass, subscriberMethods);        return subscriberMethods;    }}

从上面的逻辑可以知道,一般会调用findUsingInfo方法,我们接着看SubscriberMethodFinder#findUsingInfo方法:

findUsingInfo

private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {    //准备一个FindState,该FindState保存了订阅者类的信息    FindState findState = prepareFindState();    //对FindState初始化    findState.initForSubscriber(subscriberClass);    while (findState.clazz != null) {        //获得订阅者的信息,一开始会返回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 {            //1 、到了这里            findUsingReflectionInSingleClass(findState);        }        //移动到父类继续查找        findState.moveToSuperclass();    }    return getMethodsAndRelease(findState);}

上面用到了FindState这个内部类来保存订阅者类的信息,我们看看它的内部结构:

FindState

static class FindState {    //订阅方法的列表    final List<SubscriberMethod> subscriberMethods = new ArrayList<>();    //以event为key,以method为value    final Map<Class, Object> anyMethodByEventType = new HashMap<>();    //以method的名字生成一个method为key,以订阅者类为value    final Map<String, Class> subscriberClassByMethodKey = new HashMap<>();    final StringBuilder methodKeyBuilder = new StringBuilder(128);    Class<?> subscriberClass;    Class<?> clazz;    boolean skipSuperClasses;    SubscriberInfo subscriberInfo;    //对FindState初始化    void initForSubscriber(Class<?> subscriberClass) {        this.subscriberClass = clazz = subscriberClass;        skipSuperClasses = false;        subscriberInfo = null;    }    //省略...}

可以看出,该内部类保存了订阅者及其订阅方法的信息,用Map一一对应进行保存,接着利用initForSubscriber进行初始化,这里subscriberInfo初始化为null,因此在SubscriberMethodFinder#findUsingInfo里面,会直接调用到①号代码,即调用SubscriberMethodFinder#findUsingReflectionInSingleClass,这个方法非常重要!!!在这个方法内部,利用反射的方式,对订阅者类进行扫描,找出订阅方法,并用上面的Map进行保存,我们来看这个方法。

findUsingReflectionInSingleClass

  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();        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {            //获取方法的参数类型            Class<?>[] parameterTypes = method.getParameterTypes();            //如果参数个数为一个,则继续            if (parameterTypes.length == 1) {                //获取该方法的@Subscribe注解                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);                if (subscribeAnnotation != null) {                    //参数类型 即为 事件类型                    Class<?> eventType = parameterTypes[0];                    // 2 、调用checkAdd方法                    if (findState.checkAdd(method, eventType)) {                        //从注解中提取threadMode                        ThreadMode threadMode = subscribeAnnotation.threadMode();                        //新建一个SubscriberMethod对象,并添加到findState的subscriberMethods这个集合内                        findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,                                subscribeAnnotation.priority(), subscribeAnnotation.sticky()));                    }                }            //如果开启了严格验证,同时当前方法又有@Subscribe注解,对不符合要求的方法会抛出异常            } 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");        }    }}

虽然该方法比较长,但是逻辑非常清晰,逐一判断订阅者类是否存在订阅方法,如果符合要求,并且②号代码调用FindState#checkAdd方法返回true的时候,才会把方法保存在findState的subscriberMethods内。而SubscriberMethod则是用于保存订阅方法的一个类。那么我们来看看FindState#checkAdd做了什么工作。

checkAdd

boolean checkAdd(Method method, Class<?> eventType) {    // 2 level check: 1st level with event type only (fast), 2nd level with complete signature when required.    // Usually a subscriber doesn't have methods listening to the same event type.    Object existing = anyMethodByEventType.put(eventType, method);    if (existing == null) {        return true;    } else {        if (existing instanceof Method) {            if (!checkAddWithMethodSignature((Method) existing, eventType)) {                // Paranoia check                throw new IllegalStateException();            }            // Put any non-Method object to "consume" the existing Method            anyMethodByEventType.put(eventType, this);        }        return checkAddWithMethodSignature(method, eventType);    }}

从注释可知,这里包含两重检验,第一层检验是判断eventType的类型,而第二次检验是判断方法的完整签名。首先通过anyMethodByEventType.put(eventType, method) 将eventType以及method放进anyMethodByEventType这个Map中(上面提到),同时该put方法会返回同一个key的上一个value值,所以如果之前没有别的方法订阅了该事件,那么existing应该为null,可以直接返回true;否则为某一个订阅方法的实例,要进行下一步的判断。接着往下走,会调用checkAddWithMethodSignature()方法。

checkAddWithMethodSignature

private boolean checkAddWithMethodSignature(Method method, Class<?> eventType) {    methodKeyBuilder.setLength(0);    methodKeyBuilder.append(method.getName());    methodKeyBuilder.append('>').append(eventType.getName());    //methodKey由方法名与事件名组成    String methodKey = methodKeyBuilder.toString();    //获取当前方法所在的类的类名    Class<?> methodClass = method.getDeclaringClass();    //给subscriberClassByMethodKey赋值,并返回上一个相同key的 类名    Class<?> methodClassOld = subscriberClassByMethodKey.put(methodKey, methodClass);    if (methodClassOld == null || methodClassOld.isAssignableFrom(methodClass)) {        // Only add if not already found in a sub class        return true;    } else {        // Revert the put, old class is further down the class hierarchy        subscriberClassByMethodKey.put(methodKey, methodClassOld);        return false;    }}

从上面的代码看出,该方法首先获取了当前方法的methodKey、methodClass等,并赋值给subscriberClassByMethodKey,如果方法签名相同,那么返回旧值给methodClassOld,接着是一个if判断,判断methodClassOld是否为空,由于第一次调用该方法的时候methodClassOld肯定是null,此时就可以直接返回true了。但是,后面还有一个判断即methodClassOld.isAssignableFrom(methodClass),这个的意思是:methodClassOld是否是methodClass的父类或者同一个类。如果这两个条件都不满足,则会返回false,那么当前方法就不会添加为订阅方法了。

那么,说了一大堆关于checkAddcheckAddWithMethodSignature方法的源码,那么这两个方法到底有什么作用呢?从这两个方法的逻辑来看,第一层判断根据eventType来判断是否有多个方法订阅该事件,而第二层判断根据完整的方法签名(包括方法名字以及参数名字)来判断。下面是笔者的理解:

第一种情况:比如一个类有多个订阅方法,方法名不同,但它们的参数类型都是相同的(虽然一般不这样写,但不排除这样的可能),那么遍历这些方法的时候,会多次调用到checkAdd方法,由于existing不为null,那么会进而调用checkAddWithMethodSignature方法,但是由于每个方法的名字都不同,因此methodClassOld会一直为null,因此都会返回true。也就是说,允许一个类有多个参数相同的订阅方法

第二种情况:类B继承自类A,而每个类都是有相同订阅方法,换句话说,类B的订阅方法继承并重写自类A,它们都有着一样的方法签名。方法的遍历会从子类开始,即B类,在checkAddWithMethodSignature方法中,methodClassOld为null,那么B类的订阅方法会被添加到列表中。接着,向上找到类A的订阅方法,由于methodClassOld不为null而且显然类B不是类A的父类,methodClassOld.isAssignableFrom(methodClass)也会返回false,那么会返回false。也就是说,子类继承并重写了父类的订阅方法,那么只会把子类的订阅方法添加到订阅者列表,父类的方法会忽略

让我们回到findUsingReflectionInSingleClass方法,当遍历完当前类的所有方法后,会回到findUsingInfo方法,接着会执行最后一行代码,即return getMethodsAndRelease(findState);那么我们继续看SubscriberMethodFinder#getMethodsAndRelease方法。

getMethodsAndRelease

private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {    //从findState获取subscriberMethods,放进新的ArrayList    List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);    //把findState回收    findState.recycle();    synchronized (FIND_STATE_POOL) {        for (int i = 0; i < POOL_SIZE; i++) {            if (FIND_STATE_POOL[i] == null) {                FIND_STATE_POOL[i] = findState;                break;            }        }    }    return subscriberMethods;}

通过该方法,把subscriberMethods不断逐层返回,直到返回EventBus#register()方法,最后开始遍历每一个订阅方法,并调用subscribe(subscriber, subscriberMethod)方法,那么,我们继续来看EventBus#subscribe方法。

subscribe

在该方法内,主要是实现订阅方法与事件直接的关联,即注册,即放进我们上面提到关键的几个Map中:subscriptionsByEventType、typesBySubscriber、stickyEvents。

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.getDefault().unregister(this);

那么我们来分析注销流程是怎样实现的,首先查看EventBus#unregister

unregister

public synchronized void unregister(Object subscriber) {    //根据当前的订阅者来获取它所订阅的所有事件    List<Class<?>> subscribedTypes = typesBySubscriber.get(subscriber);    if (subscribedTypes != null) {        //遍历所有订阅的事件        for (Class<?> eventType : subscribedTypes) {            unsubscribeByEventType(subscriber, eventType);        }        //从typesBySubscriber中移除该订阅者        typesBySubscriber.remove(subscriber);    } else {        Log.w(TAG, "Subscriber to unregister was not registered before: " + subscriber.getClass());    }}

上面调用了EventBus#unsubscribeByEventType,把订阅者以及事件作为参数传递了进去,那么应该是解除两者的联系。

unsubscribeByEventType

private void unsubscribeByEventType(Object subscriber, Class<?> eventType) {    //根据事件类型从subscriptionsByEventType中获取相应的 subscriptions 集合    List<Subscription> subscriptions = subscriptionsByEventType.get(eventType);    if (subscriptions != null) {        int size = subscriptions.size();        //遍历所有的subscriptions,逐一移除        for (int i = 0; i < size; i++) {            Subscription subscription = subscriptions.get(i);            if (subscription.subscriber == subscriber) {                subscription.active = false;                subscriptions.remove(i);                i--;                size--;            }        }    }}

可以看到,上面两个方法的逻辑是非常清楚的,都是从typesBySubscriber或subscriptionsByEventType移除相应与订阅者有关的信息,注销流程相对于注册流程简单了很多,其实注册流程主要逻辑集中于怎样找到订阅方法上。

发送事件

接下来,我们分析发送事件的流程,一般地,发送一个事件调用以下代码:

EventBus.getDefault().post(new MessageEvent("Hello !....."));`

我们来看看EventBus#post方法。

post

public void post(Object event) {    //1、 获取一个postingState    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,那么PostingThreadState是什么呢?我们来看看它的类结构:

PostingThreadState

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

可以看出,该PostingThreadState主要是封装了当前线程的信息,以及订阅者、订阅事件等。那么怎么得到这个PostingThreadState呢?让我们回到post()方法,看①号代码,这里通过currentPostingThreadState.get()来获取PostingThreadState。那么currentPostingThreadState又是什么呢?

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

原来 currentPostingThreadState是一个ThreadLocal,而ThreadLocal是每个线程独享的,其数据别的线程是不能访问的,因此是线程安全的。我们再次回到Post()方法,继续往下走,是一个while循环,这里不断地从队列中取出事件,并且分发出去,调用的是EventBus#postSingleEvent方法。

postSingleEvent

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {    Class<?> eventClass = event.getClass();    boolean subscriptionFound = false;    //该eventInheritance上面有提到,默认为true,即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));        }    }}

从上面的逻辑来看,对于一个事件,默认地会搜索出它的父类,并且把父类也作为事件之一发送给订阅者,接着调用了EventBus#postSingleEventForEventType,把事件、postingState、事件的类传递进去,那么我们来看看这个方法。

postSingleEventForEventType

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {    CopyOnWriteArrayList<Subscription> subscriptions;    synchronized (this) {        //从subscriptionsByEventType获取响应的subscriptions        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;            }             //...        }        return true;    }    return false;}

接着,进一步调用了EventBus#postToSubscription,可以发现,这里把订阅列表作为参数传递了进去,显然,订阅列表内部保存了订阅者以及订阅方法,那么可以猜测,这里应该是通过反射的方式来调用订阅方法。具体怎样的话,我们看源码。

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,即订阅方法运行的线程,如果是POSTING,那么直接调用invokeSubscriber()方法即可,如果是MAIN,则要判断当前线程是否是MAIN线程,如果是也是直接调用invokeSubscriber()方法,否则会交给mainThreadPoster来处理,其他情况相类似。这里会用到三个Poster,由于粘性事件也会用到这三个Poster,因此我把它放到下面来专门讲述。而EventBus#invokeSubscriber的实现也很简单,主要实现了利用反射的方式来调用订阅方法,这样就实现了事件发送给订阅者,订阅者调用订阅方法这一过程。如下所示:

invokeSubscriber

void invokeSubscriber(Subscription subscription, Object event) {    try {        subscription.subscriberMethod.method.invoke(subscription.subscriber, event);    }     //...}

到目前为止,事件的发送流程也讲解完毕,为了方便理解,整个发送流程也给出相应的流程图:

发送流程.jpg

粘性事件的发送及接收分析

粘性事件与一般的事件不同,粘性事件是先发送出去,然后让后面注册的订阅者能够收到该事件。粘性事件的发送是通过EventBus#postSticky()方法进行发送的,我们来看它的源码:

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

把该事件放进了 stickyEvents这个map中,接着调用了post()方法,那么流程和上面分析的一样了,只不过是找不到相应的subscriber来处理这个事件罢了。那么为什么当注册订阅者的时候可以马上接收到匹配的事件呢?还记得上面的EventBus#subscribe方法里面有一段是专门处理粘性事件的代码吗?即:

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {    //以上省略...    //下面是对粘性事件的处理    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并不知道当前的订阅者对应了哪个粘性事件,因此需要全部遍历一次,找到匹配的粘性事件后,会调用EventBus#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, Looper.getMainLooper() == Looper.myLooper());    }}

接着,又回到了postToSubscription方法了,无论对于普通事件或者粘性事件,都会根据threadMode来选择对应的线程来执行订阅方法,而切换线程的关键所在就是mainThreadPoster、backgroundPoster和asyncPoster这三个Poster。

HandlerPoster

我们首先看mainThreadPoster,它的类型是HandlerPoster继承自Handler:

final class HandlerPoster extends Handler {    //PendingPostQueue队列,待发送的post队列    private final PendingPostQueue queue;    //规定最大的运行时间,因为运行在主线程,不能阻塞主线程    private final int maxMillisInsideHandleMessage;    private final EventBus eventBus;    private boolean handlerActive;    //省略...}

可以看到,该handler内部有一个PendingPostQueue,这是一个队列,保存了PendingPost,即待发送的post,该PendingPost封装了event和subscription,方便在线程中进行信息的交互。在postToSubscription方法中,当前线程如果不是主线程的时候,会调用HandlerPoster#enqueue方法:

void enqueue(Subscription subscription, Object event) {    //将subscription和event打包成一个PendingPost    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);    synchronized (this) {        //入队列        queue.enqueue(pendingPost);        if (!handlerActive) {            handlerActive = true;            //发送消息,在主线程运行            if (!sendMessage(obtainMessage())) {                throw new EventBusException("Could not send handler message");            }        }    }}

首先会从PendingPostPool中获取一个可用的PendingPost,接着把该PendingPost放进PendingPostQueue,发送消息,那么由于该HandlerPoster在初始化的时候获取了UI线程的Looper,所以它的handleMessage()方法运行在UI线程:

@Overridepublic void handleMessage(Message msg) {    boolean rescheduled = false;    try {        long started = SystemClock.uptimeMillis();        //不断从队列中取出pendingPost        while (true) {            //省略...            eventBus.invokeSubscriber(pendingPost);                    //..        }    } finally {        handlerActive = rescheduled;    }}

里面调用到了EventBus#invokeSubscriber方法,在这个方法里面,将PendingPost解包,进行正常的事件分发,这上面都说过了,就不展开说了。

BackgroundPoster

BackgroundPoster继承自Runnable,与HandlerPoster相似的,它内部都有PendingPostQueue这个队列,当调用到它的enqueue的时候,会将subscription和event打包成PendingPost:

public void enqueue(Subscription subscription, Object event) {    PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);    synchronized (this) {        queue.enqueue(pendingPost);        //如果后台线程还未运行,则先运行        if (!executorRunning) {            executorRunning = true;            //会调用run()方法            eventBus.getExecutorService().execute(this);        }    }}

该方法通过Executor来运行run()方法,run()方法内部也是调用到了EventBus#invokeSubscriber方法。

AsyncPoster

与BackgroundPoster类似,它也是一个Runnable,实现原理与BackgroundPoster大致相同,但有一个不同之处,就是它内部不用判断之前是否已经有一条线程已经在运行了,它每次post事件都会使用新的一条线程。

再谈观察者模式

整个EventBus是基于观察者模式而构建的,而上面的调用观察者的方法则是观察者模式的核心所在。

观察者模式:定义了对象之间的一对多依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新。

从整个EventBus可以看出,事件是被观察者,订阅者类是观察者,当事件出现或者发送变更的时候,会通过EventBus通知观察者,使得观察者的订阅方法能够被自动调用。当然了,这与一般的观察者模式有所不同。回想我们所用过的观察者模式,我们会让事件实现一个接口或者直接继承自Java内置的Observerable类,同时在事件内部还持有一个列表,保存所有已注册的观察者,而事件类还有一个方法用于通知观察者的。那么从单一职责原则的角度来说,这个事件类所做的事情太多啦!既要记住有哪些观察者,又要等到时机成熟的时候通知观察者,又或者有别的自身的方法。这样的话,一两件事件类还好,但如果对于每一个事件类,每一个新的不同的需求,都要实现相同的操作的话,这是非常繁琐而且低效率的。因此,EventBus就充当了中介的角色,把事件的很多责任抽离出来,使得事件自身不需要实现任何东西,别的都交给EventBus来操作就可以了。

好了,本文到此为止已经对EventBus进行了一次详细的讲解,由于本文很长,建议读者可以选择难懂的部分对照源码反复思考以便能深刻理解。最后,为坚持读完本文的你点赞,谢谢你们的阅读!