EventBus全解析系列(三)

EventBus 事件分发源码分析

承接上篇我们讲了EventBus的注册和反注册,本篇我们来讲解EventBus的事件分发,即post一个事件之后怎么传达到对应的订阅者的。先简单的描述下大体过程:
从EventBus的总线LIst中找出订阅了这个event的方法Subscription,然后根据Subscription中的method指定的不同线程信息,将这个方法放置在相应线程中调用。

Post 源码分析

一步一步进行源码解析,先从入口post方法看起:

private final ThreadLocal currentPostingThreadState = new ThreadLocal() {
    @Override
    protected PostingThreadState initialValue() {
        return new PostingThreadState();
    }
};
/** Posts the given event to the event bus. */
public void post(Object event) {
    //currentPostingThreadState是一个ThreadLocal,他的特点是获取当前线程一份独有的变量数据,不受其他线程影响。
    PostingThreadState postingState = currentPostingThreadState.get();
    //postingState就是获取到的线程独有的变量数据 
    List eventQueue = postingState.eventQueue;
    //把post的事件添加到事件队列
    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;
        }
    }
}

/** For ThreadLocal, much faster to set (and get multiple values). */
final static class PostingThreadState {
    //事件队列
    final List eventQueue = new ArrayList();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}
 
 

在 post方法中,大致流程为 :

  • 首先根据 currentPostingThreadState 获取当前线程状态 postingState 。currentPostingThreadState 其实就是一个 ThreadLocal 类的对象,不同的线程根据自己独有的索引值可以得到相应属于自己的 postingState 数据。
  • 然后把事件 event 加入到 eventQueue 队列中排队。
  • 循环遍历 eventQueue ,取出事件发送事件。发送单个事件是调用 postSingleEvent(Object event, PostingThreadState postingState) 方法。

我们跟进去看postSingleEvent方法源码:

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    // 得到事件的类型
    Class eventClass = event.getClass();
    // 是否找到订阅者
    boolean subscriptionFound = false;
    // 如果支持事件继承,默认为支持
    if (eventInheritance) {
        // 查找 eventClass 的所有父类和接口
        List> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {
            Class clazz = eventTypes.get(h);
            // 依次向 eventClass 的父类或接口的订阅方法发送事件
            // 只要有一个事件发送成功,返回 true ,那么 subscriptionFound 就为 true
            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) {
            // 发送 NoSubscriberEvent 事件,可以自定义接收
            post(new NoSubscriberEvent(this, event));
        }
    }
}

在postSingleEvent方法中,事件发送根据 eventInheritance 分成两种,大致流程为:

  • eventInheritance 默认为true,支持事件继承:得到 eventClass 的所有父类和接口,然后循环依次发送事件;
  • eventInheritance 默认为false,不支持事件继承:直接发送eventClass 事件。
  • 若找不到订阅者,默认会发送 NoSubscriberEvent 事件。开发者可以自定义订阅方法接收这个事件。

关于事件发送的具体操作进一步到 postSingleEventForEventType方法中去看:

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class eventClass) {
    CopyOnWriteArrayList 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;
}

postSingleEventForEventType方法主要做的事情:

  • 从订阅者注册列表中取出eventClass事件对应的订阅者列表,
  • 遍历了订阅者,然后依次调用 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);
    }
}

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

postToSubscription 方法中,根据 threadMode 不同将事件按发送线程模式 共分为四种:

  • (POSTING)同一个线程:表示订阅方法所处的线程和发布事件的线程是同一个线程;
  • (MAIN)主线程:如果发布事件的线程是主线程,那么直接执行订阅方法;否则利用 Handler 回调主线程来执行;
  • (BACKGROUND)子线程:如果发布事件的线程是主线程,那么调用线程池中的子线程来执行订阅方法;否则直接执行;
  • (ASYNC)异步线程:无论发布事件执行在主线程还是子线程,都利用一个异步线程来执行订阅方法。
    这四种线程模式其实最后都会调用 invokeSubscriber(Subscription subscription, Object event) 方法通过反射来调用注册的方法,从而实现了将事件event发送的了对应的注册者方法里处理。

至此,整个 EventBus 发布的源码解析就讲完了。整个代码流程整体是线性,最后附上流程图:

EventBus全解析系列(三)_第1张图片
post1.png

你可能感兴趣的:(EventBus全解析系列(三))