EventBus源码分析

前面对EventBus 的简单实用写了一篇,相信大家都会使用,如果使用的还不熟,或者不够6,可以花2分钟瞄一眼:https://www.jianshu.com/p/321108571fd0

源码分析准备工作

原因:好多同事同学最近出去面试都问,其实我很早前看过了,现在记不住了,而且自己使用的东西最好知道所以然
版本:EventBus 3.0

源码结构图

EventBus源码分析_第1张图片
EventBus.png

获取实例并注册

EventBus.getDefault().register(this);

1.getDefault()的源码是怎样的,代码如下,很明显是单例模式!双重锁校验,并且实例使用了关键字volatile 修饰,保证线程安全,简单说一下volatile,只作用于变量,让变量在各个线程可见的。不能保证原子性,比如i++ ,分3步,从内存读出i ,然后i++ ,然后在写到内存,这也是内存模型的知识,也就是 可能在第一步还没搞完,就读回去了,这个一般区别synchronized ,synchronized 有可能会造成线程阻塞,不多说了,回到本质。

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

2.我们继续看下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(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);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

构造使用的public 修饰?不怕我创建对象吗,我在看源码时就比较好奇,发现他的注释:创建事件总线实例都在他的范围内,推荐我们用中央bus考虑使用单例!也就是每一个EventBus都是独立地、处理它们自己的事件,因此可以存在多个EventBus而通过getDefault()方法获取的实例,则是它已经帮我们构建好的EventBus,是单例,无论在什么时候通过这个方法获取的实例都是同一个实例。

进行了一堆成员变量的初始化操作,重点看下这几个关键的成员变量,看下等会他们干什么的

private final Map, CopyOnWriteArrayList> subscriptionsByEventType;
private final Map>> typesBySubscriber;
private final Map, Object> stickyEvents;
subscriptionsByEventType

以event(即事件类)为key,以订阅列表(Subscription)为value,事件发送之后,在这里寻找订阅者
而Subscription又是一个CopyOnWriteArrayList,这是一个线程安全的容器 ,Subscription是一个封装类,封装了订阅者、订阅方法这两个类。它的构造如下:

   Subscription(Object subscriber, SubscriberMethod subscriberMethod) {
        this.subscriber = subscriber;
        this.subscriberMethod = subscriberMethod;
        active = true;
    }
typesBySubscriber

以订阅者类为key,以event事件类为value,在进行register或unregister操作的时候,会操作这个hashmap

stickyEvents

保存的是粘性事件
接下来实例化了三个Poster,分别是mainThreadPoster、backgroundPoster、asyncPoster等,这三个Poster是用来处理粘性事件的,然后使用建造者模式对

EventBusBuilder,它的一系列方法用于配置EventBus的属性,使用getDefault()方法获取的实例,会有着默认的配置,上面说过,EventBus的构造方法是公有的,所以我们可以通过给EventBusBuilder设置不同的属性,进而获取有着不同功能的EventBus。

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

EventBus eventBus = EventBus.builder()
        .eventInheritance(false) //默认地,EventBus会考虑事件的超类,即事件如果继承自超类,那么该超类也会作为事件发送给订阅者如果设置为false,则EventBus只会考虑事件类本身
        .sendNoSubscriberEvent(true)
        .skipMethodVerificationFor(MainActivity.class)
        .build();

注册

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

1.注册: register()

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

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

private static final Map, List> METHOD_CACHE = new ConcurrentHashMap<>();
....

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

        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 {
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

这个里面就是传入注册的类,首先是从METHOD_CACHE这个ConcurrentHashMap 里面获取,而这个map 存放的是key :类。value 就是所有的订阅方法放在list中,如果获取到就返回这个订阅方法的list 没有缓存,继续往下走,通过EventBus 的构造可以知道,这个标志位。ignoreGennerratedIndex 默认false 就是在建造者初始化时候,一般会调用findUsingInfo方法:

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

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

 static class FindState {
        final List subscriberMethods = new ArrayList<>();
        final Map anyMethodByEventType = new HashMap<>();
        final Map subscriberClassByMethodKey = new HashMap<>();
        final StringBuilder methodKeyBuilder = new StringBuilder(128);

        Class subscriberClass;
        Class clazz;
        boolean skipSuperClasses;
        SubscriberInfo subscriberInfo;

        void initForSubscriber(Class subscriberClass) {
            this.subscriberClass = clazz = subscriberClass;
            skipSuperClasses = false;
            subscriberInfo = null;
        }

       ....

该内部类保存了订阅者及其订阅方法的信息,用Map一一对应进行保存,接着利用initForSubscriber进行初始化,这里subscriberInfo初始化为null ,所以,findUsingInfo方法中会调用findUsingReflectionInSingleClass(findState)

在这个方法中利用反射的方式,对订阅者类进行扫描,找出订阅方法,并用上面的Map进行保存,我们来看这个方法 逐一判断订阅者类是否存在订阅方法,如果符合要求,调用findState.checkAdd(method, eventType)返回true的时候,才会把方法保存在findState的subscriberMethods内。而SubscriberMethod则是用于保存订阅方法的一个类
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 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");
            }
        }
    }

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()方法

private boolean checkAddWithMethodSignature(Method method, Class eventType) {
            methodKeyBuilder.setLength(0);
            methodKeyBuilder.append(method.getName());
            methodKeyBuilder.append('>').append(eventType.getName());

            String methodKey = methodKeyBuilder.toString();
            Class methodClass = method.getDeclaringClass();
            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,那么当前方法就不会添加为订阅方法了

checkAdd和checkAddWithMethodSignature方法的源码,那么这两个方法到底有什么作用呢?从这两个方法的逻辑来看,第一层判断根据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方法

private List getMethodsAndRelease(FindState findState) {
    //从findState获取subscriberMethods,放进新的ArrayList
    List 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

// Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        Class eventType = subscriberMethod.eventType;
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        CopyOnWriteArrayList 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> 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).
                Set, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry, 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);
            }
        }
    }

订阅方法中,将订阅类和订阅方法,封装成一个Subscription 对象,再据事件类型获取特定的 Subscription,如果为null,说明该subscriber尚未注册该事件 如果不为null,并且包含了这个subscription 那么说明该subscriber已经注册了该事件,抛出异常
根据优先级来设置放进subscriptions的位置,优先级高的会先被通知
根据subscriber(订阅者)来获取它的所有订阅事件

注册流程基本分析完毕,而关于最后的粘性事件的处理,这里暂时不说,下面会详细进行讲述。可以看出,整个注册流程非常地长,方法的调用栈很深,在各个方法中不断跳转,那么为了方便读者理解,下面给出一个流程图,读者可结合该流程图以及上面的详解来进行理解。

注销

与注册相对应的是注销,当订阅者不再需要事件的时候,我们要注销这个订阅者,即调用以下代码:

EventBus.getDefault().unregister(this);

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

unregister

public synchronized void unregister(Object subscriber) {
    //根据当前的订阅者来获取它所订阅的所有事件
    List> 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 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方法。

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

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

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

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

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

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class eventClass = event.getClass();
    boolean subscriptionFound = false;
    //该eventInheritance上面有提到,默认为true,即EventBus会考虑事件的继承树
    //如果事件继承自父类,那么父类也会作为事件被发送
    if (eventInheritance) {
        //查找该事件的所有父类
        List> 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 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);
    } 
    //...
}

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

粘性事件与一般的事件不同,粘性事件是先发送出去,然后让后面注册的订阅者能够收到该事件。粘性事件的发送是通过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).
            //从列表中获取所有粘性事件,由于粘性事件的性质,我们不知道它对应哪些订阅者,
            //因此,要把所有粘性事件取出来,逐一遍历
            Set, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry, 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线程:

@Override
public 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源码分析)