EventBus3.0 源码解析

简介

我们知道,Android应用主要是由4大组件构成。当我们进行组件间通讯时,由于位于不同的组件,通信方式相对麻烦。基于此,EventBus便油然而生。通过EventBus,我们可以很轻松的进行组件间通信。

使用方法

EventBus in 3 steps

Define events:

public static class MessageEvent { /* Additional fields if needed */ }

Prepare subscribers: Declare and annotate your subscribing method, optionally specify a thread mode:

@Subscribe(threadMode = ThreadMode.MAIN)
 public void onMessageEvent(MessageEvent event) {/* Do something */};

Register and unregister your subscriber. For example on Android, activities and fragments should usually register according to their life cycle:

@Override 
public void onStart() { 
    super.onStart(); 
    EventBus.getDefault().register(this); 
} 
 @Override
 public void onStop() { 
     super.onStop();
     EventBus.getDefault().unregister(this); 
}

Post events:

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

Read the full getting started guide.

源码解析

EventBus的使用,无外乎主要就是订阅,事件发送和解除订阅3大步骤,那么源码解析我们也从这3个方面进行入手。

(1). 订阅

使用EventBus时,第一步肯定是先进行注册,通常使用的就是:

EventBus.getDefault().register(this);

那我们就先来看下:EventBus.getDefault()

public EventBus() {
        this(DEFAULT_BUILDER);
    }

 /** Convenience singleton for apps using a process-wide EventBus instance. */
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

可以看到,getDefault()其实就是用的双重锁校验来实现一个单例EventBus,但是跟普通的单例模式不同的是,EventBus的默认构造函数确是public的,其实这里的public是有深层含义的,当我们使用getDefault()时获取的EventBus,只是一条事件总线,如果我们想构造多条事件总线,那么我们就可以直接实例化EventBus即可
接下来我们来看下EventBus的注册过程:

/**
     * Registers the given subscriber to receive events. Subscribers must call {@link #unregister(Object)} once they
     * are no longer interested in receiving events.
     * <p/>
     * Subscribers have event handling methods that must be annotated by {@link Subscribe}.
     * The {@link Subscribe} annotation also allows configuration like {@link
     * ThreadMode} and priority.
     */
    public void register(Object subscriber) {
        Class<?> subscriberClass = subscriber.getClass();
        //找到subscriber源文件(及其父类)中注册的事件方法
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                //按事件将所有的subscirber记录下来,并依据priority进行排序,
                // 如果是sticky事件,则从粘性记录中查找是否前面已经分发了该事件通知,
                // 如果是,则立即调用该subscriber的subscriberMethod。
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

从register源代码可以看到,注册过程主要分为2个步骤:
1.通过findSubscriberMethods()方法,就可以找到对应subscriber中注册的事件方法;
2.subscribe()过程,记录subscriber并排序,对注册者进行粘性事件调用···

那首先,我们先分析下findSubscriberMethods(),其具体的查找过程如下:

 List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass);
        if (subscriberMethods != null) {
            return subscriberMethods;
        }
 //是否忽略从注解器生成的MyEventBusIndex类获取事件方法,默认为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 {
            //将subscriberClass类(连同父类)对应的@Subscribe方法进行缓存
            METHOD_CACHE.put(subscriberClass, subscriberMethods);
            return subscriberMethods;
        }
    }

METHOD_CACHE是一个全局静态的ConcurrentHashMap,

private static final Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>();

从METHOD_CACHE中我们可以得知,它会缓存所有事件总线的所有subscriber对应的所有事件方法。
EventBus3.0相对于之前的版本,性能上有了很大的提升,提升的主要原因就在于事件信息的获取来源:旧版本事件信息都是通过采用反射来获取,而新版本默认是采用编译器注解方式(如果还不清楚注解处理器的内容,可以参考下我之前的简文:注解处理器(Annotation Processor)简析),在编译的时候通过@Subscribe注解获取事件信息,从而在效率上得到很大的提升。
所以,register中,findUsingReflection(subscriberClass)采用的便是运行时反射获取,findUsingInfo(subscriberClass)采用的就是从apt自动生成的MyEventBusIndex类中获取事件信息。

这里,我们就只对findUsingInfo()进行分析:

 /**
     *
     * @param subscriberClass
     * @return 获取subscriberClass及其父类的@Subscribe方法
     */
    private List<SubscriberMethod> findUsingInfo(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
        //从apt自动生成的MyEventBusIndex类中获取SubscriberInfo
            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的设计采用享元模式,避免FindState的频繁创建,具体详情可以查看附录介绍。

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

findState.initForSubscriber(subscriberClass)中,我们可以得知findState.subscriberClass = findState.clazz = subscriberClass != null,所以findUsingInfo会进入while循环。进入循环后,这里有一个很重要的动作就是:getSubscriberInfo

 private SubscriberInfo getSubscriberInfo(FindState findState) {
                 ···
                 ···
        //由EventBusBuillder从apt自动生成的类中获取
        if (subscriberInfoIndexes != null) {
            for (SubscriberInfoIndex index : subscriberInfoIndexes) {
                //取得Subscriber类的相关信息:Subscriber类,@Subscribe相关方法等
                SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
                if (info != null) {
                    return info;
                }
            }
        }
        return null;
    }
//SubscriberMethodFinder
private List<SubscriberInfoIndex> subscriberInfoIndexes;

如果subscriberInfoIndexes != null,那么就可以从其得到SubscriberInfo。看到这里,我们就有疑问了,你说subscriberInfoIndexes != null,那么它是在哪被赋值的呀?这里,我们就来回顾一下了,因为subscriberInfoIndexes是SubscriberMethodFinder类的成员变量,所以很自然我们会找一些SubscriberMethodFinder在哪里会对subscriberInfoIndexes进行赋值,

SubscriberMethodFinder(List<SubscriberInfoIndex> subscriberInfoIndexes, boolean strictMethodVerification,
                           boolean ignoreGeneratedIndex) {
        this.subscriberInfoIndexes = subscriberInfoIndexes;
        this.strictMethodVerification = strictMethodVerification;
        this.ignoreGeneratedIndex = ignoreGeneratedIndex;
    }

查看后,我们知道SubscriberMethodFinder是在构造函数中对subscriberInfoIndexes进行赋值,那么我们接下来应该寻找的就是SubscriberMethodFinder是在哪里被实例化,还记得我们EventBus.register里面有一句:

subscriberMethodFinder.findSubscriberMethods(subscriberClass);

原来SubscriberMethodFinder的一个实例化就在EventBus中,那么我们就来查看下EventBus具体在哪个地方对其进行创建:

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;
        //index speed
        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;
    }

可以看到,SubscriberMethodFinder是在EventBus构造函数中被实例化的,然后SubscriberMethodFinder.subscriberInfoIndexes指向的是builder.subscriberInfoIndexes,而EventBusBuilder是通过addIndex()对subscriberInfoIndexes进行创建赋值的。


    /** Adds an index generated by EventBus' annotation preprocessor. */
    public EventBusBuilder addIndex(SubscriberInfoIndex index) {
        if(subscriberInfoIndexes == null) {
            subscriberInfoIndexes = new ArrayList<>();
        }
        subscriberInfoIndexes.add(index);
        return this;
    }

所以,如果想让EventBus从apt中进行数据获取,还要通过显示构建一个EventBusBuilder,并调用
EventBus.builder().addIndex(new MyEventBusIndex()).build()方法进行创建赋值。
具体的做法如下:参考官方文档

现在让我们回到findUsingInfo方法中,如果getSubscriberInfo == null,那么它也会通过反射进行事件信息获取。也就是说,如果你本意想通过apt进行数据获取,但是可能由于不小心缺少了相应步骤配置,导致无法从apt获取,那么,程序会自动采用反射进行获取。结果是可以成功运行的,只是效率低了许多。

现在假设我们成功配置了apt,那么findUsingInfo就会进入下面代码:

 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);
                    }
                }
            }
···
 findState.moveToSuperclass();
}

这部分代码最终就会获取到subscriberClass及其父类的@Subscribe方法存放到 findState.subscriberMethods中,最终返回给上层调用。
以上,查找事件信息过程就已结束了。

接下来,我们来看下subscribe过程:

/**
     *
     * @param subscriber
     * @param subscriberMethod
     * Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
     * subscriptionsByEventType中存储的就是事件对应的监听组信息。
     * 由事件获取得到监听组,然后新的subscriber和SubscriberMethod按priority存放进同一event的
     * CopyOnWriteArrayList<Subscription>中.
     *
     * 如果当前的Subscriber事件方法是sticky的,则从stickyEvents记录中查找看是否有与本方法事件
     * 相同的事件(即之前已经有组件发送该粘性事件{@link #postSticky(Object)},如果有,则立即
     * 调用本方法。
     */
    // 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;
            }
        }

        //记录subscriber对应的所有事件类型
        List<Class<?>> 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<Class>).
                Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
                for (Map.Entry<Class<?>, Object> entry : entries) {
                    Class<?> candidateEventType = entry.getKey();
                    //candidateEventType跟eventType是否是同一类型
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

可以看出,subscribe过程主要做了3件事:
1.将当前的subscriberMethod按priority添加到subscriptionsByEventType中的同一evenType中
2.将当前事件eventType添加到当前subscriber的事件集合中,映射关系表由typesBySubscriber记录
3.如果当前事件是粘性事件,那么从系统保存的粘性发送事件stickyEvents中,找寻与当前事件相同(或与当前事件类型有继承关系)的事件,取出事件参数,并立即调用当前事件方法,传入事件参数。

最后,以一张图来显示register过程:


EventBus::register

(2). 事件分发

接下来,我们来看一下EventBus的事件分发过程:

 /** Posts the given event to the event bus. */
    public void post(Object event) {
        //取得post线程当前状态
        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;
            }
        }
    }

可以看到,post过程首先做的是取出当前线程的线程状态,currentPostingThreadState是一个ThreadLocal对象,这样可以很好的保证在不同的线程中都拥有一份线程独立的PostingThreadState对象。
post过程首先取出当前线程状态对象:PostingThreadState postingState ,然后将当前分发的事件添加进线程对象postingState中,最后,如果当前线程不处于分发状态,那么就循环遍历当前线程所有分发事件,取出事件进行分发。分发函数为:postSingleEvent

 private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        //eventInheritance:是否支持事件继承分发,默认为true
        if (eventInheritance) {
            //存储eventClass及其父类/接口,
            // 即发送一个事件,那么注册该事件以及该事件的父类/接口的订阅者都会收到该事件通知
            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);
            }
            //则发送一个NoSubscriberEvent事件
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

postSingleEvent为单个事件分发流程,eventInheritance标志事件是否支持继承分发,默认为true(可以在EventBusBuilder中查看到),即EventBus默认会分发该事件到注册该事件或者该事件父类/接口的订阅者事件函数中。所以,postSingleEvent主要做了2件事:
1.判断是否支持事件继承分发:如果支持,那么就通过当前事件class对象,找到其父类/接口所有事件类型,然后循环取出每个事件类别,依次调用postSingleEventForEventType进行实际的事件分发;如果不支持事件继承分发,那么就直接将当前事件分发给当前事件订阅者。
2.如果当前分发事件没有对应的订阅者,那么就会发送一个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;
    }

原来,事件分发给订阅者主要做的就是:从之前register的订阅者事件集合subscriptionsByEventType中,通过当前事件,得到对应的订阅者集合,结合当前的post线程对象状态,依次调用postToSubscription真正地将事件分发给各个订阅者。

我们知道,在使用EventBus过程中,我们可以在不同的线程post事件,然后订阅该事件的事件函数会根据threadMode会自动进行线程切换,那这是怎样做到的呢?想了解清楚这点,那么我们就要看一下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);
        }
    }

这里,我们可以看到,postToSubscription会根据每个订阅者的事件函数的threadMode标识,对应当前线程状态,进行线程间转换,从而保证了订阅者事件函数会运行在与threadMode指定的线程中。
从源码中,我们可以看到,具体的threadMode所对应的线程为:

  • POSTING:订阅者事件函数运行在与post线程同一线程。
  • MAIN:如果post线程是主线程,那么直接调用订阅者事件函数;如果post不是在主线程,那么通过mainThreadPoster将订阅者函数切换到主线程上运行。
  • BACKGROUND:如果调用者是主线程,那么通过backgroundPoster将订阅者事件函数切换到后台线程上运行,反之则在post线程上直接运行。
  • ASYNC:无论post处于哪个线程,都会直接重开一条线程执行订阅者函数。

我们看到,post事件后,如果是处于同一条执行线程,EventBus是通过invokeSubscriber()函数让订阅者函数得到回调,具体做法如下:

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

其实就是通过反射进行方法调用。

然后如果是要进行线程切换回调订阅者事件函数,则是采用各种Poster的enqueue方法,那么,我们接下来就来看下它们是具体怎样进行线程切换的。

  • ** 切换到主线程:mainThreadPoster.enqueue(subscription, event)**

首先,mainThreadPoster是一个HandlerPoster对象:

final class HandlerPoster extends Handler {

    private final PendingPostQueue queue;
    private final int maxMillisInsideHandleMessage;
    private final EventBus eventBus;
    private boolean handlerActive;

    HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
        super(looper);
        this.eventBus = eventBus;
        this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
        queue = new PendingPostQueue();
    }

    void enqueue(Subscription subscription, Object event) {
        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");
                }
            }
        }
    }

    @Override
    public void handleMessage(Message msg) {
        boolean rescheduled = false;
        try {
            long started = SystemClock.uptimeMillis();
            while (true) {
                PendingPost pendingPost = queue.poll();
                if (pendingPost == null) {
                    synchronized (this) {
                        // Check again, this time in synchronized
                        pendingPost = queue.poll();
                        if (pendingPost == null) {
                            handlerActive = false;
                            return;
                        }
                    }
                }
                eventBus.invokeSubscriber(pendingPost);
                long timeInMethod = SystemClock.uptimeMillis() - started;
                if (timeInMethod >= maxMillisInsideHandleMessage) {
                    if (!sendMessage(obtainMessage())) {
                        throw new EventBusException("Could not send handler message");
                    }
                    rescheduled = true;
                    return;
                }
            }
        } finally {
            handlerActive = rescheduled;
        }
    }
}

在回顾下EventBus的构造函数,可以看到:

 EventBus(EventBusBuilder builder) {
       ···
      ···
       mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
      ···
      ···

可以看到,mainThreadPoster就是一个主线程的Handler,然后再enqueue的时候,先用一个PendingPost保存一下当前的订阅者信息和事件,并存储到一个queue中,然后通过sendMessage()给自己发了一个消息,那么自然handleMessage()就会得到回掉,然后在HandlerPoster的handleMessage中可以看到,它通过在queue中获取先前存入的事件信息后,调用了eventBus.invokeSubscriber(pendingPost):

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

所以invokeSubscriber最终也是采用发射的方式调用到了订阅者的事件函数,而且由于是在主线程Handler的handlerMessage中调用,那么订阅者事件函数肯定是运行在主线程中的。

  • ** 切换到后台线程: backgroundPoster.enqueue(subscription, event)**
    backgroundPoster是一个BackgroundPoster对象:
final class BackgroundPoster implements Runnable {

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        synchronized (this) {
            queue.enqueue(pendingPost);
            if (!executorRunning) {
                executorRunning = true;
                eventBus.getExecutorService().execute(this);
            }
        }
    }

    @Override
    public void run() {

        while (true) {
            PendingPost pendingPost = queue.poll(1000);
                    ···
            eventBus.invokeSubscriber(pendingPost);
                    ···
            executorRunning = false;
        }
         
    }

以上代码经过简化,可以看到BackgroundPoster就是一个Runnable,然后enqueue的时候,也是把订阅者相关信息和事件存储到一个PendingPost 中,最后通过线程池的方式执行自身,那么自己的run()方法就会得到调用,而run()方法里面做的就是从queue中获取数据,最后调用方式方式回调订阅者事件函数。这里有一点要注意的就是,BackgroundPoster在线程池执行一个任务时,executorRunning是会被置成true的,完成一个任务后,才会被重置成false,也就是说,BackgroundPoster的任务是串行运行的。

  • ** 新开线程:asyncPoster.enqueue(subscription, event)**
    asyncPoster是一个AsyncPoster对象:
/**
 * Posts events in background.
 * 
 * @author Markus
 */
class AsyncPoster implements Runnable {

    private final PendingPostQueue queue;
    private final EventBus eventBus;

    AsyncPoster(EventBus eventBus) {
        this.eventBus = eventBus;
        queue = new PendingPostQueue();
    }

    public void enqueue(Subscription subscription, Object event) {
        PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
        queue.enqueue(pendingPost);
        eventBus.getExecutorService().execute(this);
    }

    @Override
    public void run() {
        PendingPost pendingPost = queue.poll();
        if(pendingPost == null) {
            throw new IllegalStateException("No pending post available");
        }
        eventBus.invokeSubscriber(pendingPost);
    }
}

从AsyncPoster源码中可以看到,其实现机制与BackgroundPoster是基本一致的。唯一值得注意的是,AsyncPoster来一个任务就立即执行,也就是说AsyncPoster的任务是并行运行的

综上:对于EventBus的线程切换逻辑,他们的做法其实原理基本一致:
都是通过将订阅者相关信息和事件存储到一个队列里面,然后再异步从相关回调(对于Handler来说就是handlerMessage(),对于线程池来说就是Runnable.run())中,反射执行订阅者事件函数,从而达成线程切换这一功能。

用一张图来说明下post过程:


EventBus::post

register,post都讲了,最后,再说一下unregister就圆满了。

(3). 解除订阅

unregister过程:

/** Unregisters the given subscriber from all event classes. */
    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());
        }
    }

 /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */
    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--;
                }
            }
        }
    }

源码中可以看出,unregister主要就是做了2件事:

  1. 由订阅者subscriber从typesBySubscriber中取出当前订阅者订阅的所有事件集合。
  2. 遍历订阅事件,依次取出一个事件,然后从subscriptionsByEventType中获得所有订阅该事件的订阅者集合,从中找到该取消注册的subscriber,将其active状态设为false,并从该事件集合中删除。


    EventBus::unregister

最后,文字总结下:
Register过程:
注册过程主要执行2个操作:

  1. 由当前订阅者subscriber,通过apt或者反射方式获取当前subscriber及其父类事件订阅函数(@Subscribe).
  2. subscribe过程,subscribe就是订阅者的注册过程,该过程会将当前订阅者与其(及其父类)订阅方法记录起来,主要做以下4大操作:
    1). 依据上面获取到的事件集合,对每一个事件进行操作。依据事件类别,从subscriptionsByEventType取出所有订阅该事件的订阅者集合(没有订阅,则进行记录创建)。
    2). 依据当前事件的priority插入到订阅者集合中,从而实现优先级事件。
    3). 将当前事件存储到当前订阅者subscriber的事件集合中,方便后续unregister(依据subscriber获取得到subscriber的事件集合,再遍历事件集合,从各个事件注册集合中,删除该subscriber)。
    4). 如果当前事件是sticky事件,那么就从stickyEvents集合中(postSticky()会记录事件类型和事件实例)获取得到事件实例,并让当前订阅者subscriber进行调用。

Post过程:
post过程就是一个事件分发过程,其最基础的元素就是事件
post一个事件的时候,主要经历以下4大历程:

  1. 将当前事件添加到当前线程状态事件列表中
  2. 循环取出当前线程事件,依次进行事件分发:
  • 如果当前事件总线支持事件继承分发,那么就获取当前事件及其所有父类/接口类别,存储到集合中,然后遍历集合,依次按照事件类别进行分发;
  • 如果当前事件总线不支持事件继承分发,那么直接将当前事件进行分发;
  • 如果未找到当前事件订阅者(没有订阅),则post一个NoSubscriberEvent事件
  1. 根据当前事件类别,进行事件分发。事件分发首先从注册记录中找到该事件类别的订阅者集合,然后遍历订阅者集合,进行单个订阅者事件分发。
  2. 进行单个订阅者事件分发会依据订阅者事件函数threadMode以及当前线程状态(是否是mainThread),自动进行线程切换。

Unregister过程:
unregister过程主要也是由2个操作:

  1. 由当前要unregister的订阅者subscriber,获取得到其订阅的所有事件集合。
  2. 遍历上面得到的事件集合,依据事件从subscriptionsByEventType中取出所有订阅了该事件的订阅者集合,从中找到这个要unregister的订阅者,将其active状态设为false,并从事件集合中进行删除,这样,就完成了unregister过程。

附录

to be continue

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,425评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,058评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,186评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,848评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,249评论 3 286
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,554评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,830评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,536评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,239评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,505评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,004评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,346评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 32,999评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,060评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,821评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,574评论 2 271
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,480评论 2 267

推荐阅读更多精彩内容