EventBus3.0源码分析

前言

本篇博客基于 EventBus3.0,关于EventBus 的使用,可以去官方文档查看,或者看我以前的博客都在说EventBus,我也来一波EventBus。 这篇博客, 只说源码,不说使用 ,只说源码,不说使用,只说源码,不说使用

EventBus3.0 做出了 挺大的改变,抛弃了可读性极差的 OnEvent 开头的方法,改用注解的形式来。

@Subscribe(sticky = true, threadMode = ThreadMode.MAIN,priority = 100)
public void test(String string) {
Log.e("cat", "str:" + string);
}

大概像这样。既然使用了注解,那么是使用反射来寻找接收事件的方法吗?答案是 No。EventBus 提供了一个 EventBusAnnotationProcessor,允许通过注解在编译时生成文件的形式,这种跟 Dagger2 以及 Butterknife 是极为相似的。既拥有省去编写模板代码的能力,也不会因为使用反射而带来的性能损失。当然,编译注解是可选项,如果不使用这个,还是会使用反射,这个从后面的源码可以看出来,关于用法, 官方文档,不用谢我。Subscriber Index

源码分析

类作用分析

在讲源码之前,先把几个比较重要的类说下,以免造成混乱。

SubscribeMethod

//其实就是把接收事件方法上面的注解封装成一个 SubscribeMethod
public class SubscriberMethod {
 final Method method;
 final ThreadMode threadMode;
 final Class<?> eventType;
 final int priority;
 final boolean sticky;
 /** Used for efficient comparison */
 String methodString;
}

Subscription

// 将订阅者以及订阅的方法封装成一个 Subscritpion
final class Subscription {
final Object subscriber;
final SubscriberMethod subscriberMethod;
/**
 * Becomes false as soon as {@link EventBus#unregister(Object)} is called, which is checked by queued event delivery
 * {@link EventBus#invokeSubscriber(PendingPost)} to prevent race conditions.
 */
volatile boolean active;

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

PostingThreadState

// 存储线程信息、订阅者以及事件。post 事件的时候会用到
/** For ThreadLocal, much faster to set (and get multiple values). */
final static class PostingThreadState {
    final List<Object> eventQueue = new ArrayList<Object>();
    boolean isPosting;
    boolean isMainThread;
    Subscription subscription;
    Object event;
    boolean canceled;
}

PendingPost

// 将事件以及订阅者封装成一个 PendingPost,这个主要是切换线程的时候会用到,后面会说到。
final class PendingPost {
    private final static List<PendingPost> pendingPostPool = new ArrayList<PendingPost>();

    Object event;
    Subscription subscription;
    PendingPost next;

HandlerPost

// 将事件发送到主线程执行的 handler。
final class HandlerPoster extends Handler {
    private final PendingPostQueue queue;
    private final int maxMillisInsideHandleMessage;
    private final EventBus eventBus;
    private boolean handlerActive;
}

BackgroudPoster

// EventBus 内部有维护一个Executors.newCachedThreadPool 的线程池,当调用 BackGroudPost.enqueue 的时候,会将事件弄到线程池中执行。
// BackGroundPost是一个 Runnable, 内部维护一个队列,在 run 方法中会不断的从队列中取出 PendingPost,当队列没东东时,至多等待1s,然后跳出 run 方法。
final class BackgroundPoster implements Runnable {
    private final PendingPostQueue queue;
    private final EventBus eventBus;

    private volatile boolean executorRunning;
}

AsyncPoster

// AsyncPoster 的实现跟 BackgroundPoster 的实现极为类似,区别就是是否有在 run 方法中循环取出 PendingPost。
// 虽然相似,但是主要的不同点就是,asyncPost 会确保每一个任务都会在不同的线程中执行,而 BackgroundPoster 则如果发送的速度比较快且接收事件都是在 background 中,则会在同一线程中执行。
class AsyncPoster implements Runnable {

    private final PendingPostQueue queue;
    private final EventBus eventBus;

好了,几个重要的类都介绍完了,接下来开始主要流程的分析。

EventBus 的构建

EventBus 同样允许使用 Builder 的形式来进行构建,不过在实际使用当中,一般用的都是默认实现。同时,EventBus 也是一个单例。单例实现的代码我就不贴了,太简单。

public EventBus() {
    this(DEFAULT_BUILDER);
}

EventBus(EventBusBuilder builder) {
    subscriptionsByEventType = new HashMap<>();//以事件类型为 key,subscription list 为 value 的 map。
    typesBySubscriber = new HashMap<>();// 以订阅者为 key,订阅的事件的 list 为 value map
    stickyEvents = new ConcurrentHashMap<>();// 以事件的类型为 key,事件对象为 value 的 map。
    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; // 是否使用事件类型的继承,如果为 true,例如参数为 string 类型的方法,参数为 object 类型的方法同样也能接收到事件。
    executorService = builder.executorService;//线程池,实现类为 Executors.newCachedThreadPool()
}

上面的属性看起来挺多的,现在看不懂不要紧,看个大概就好,没注释的可能前面说过了,或者后面讲的源码没有提及。

注册 Subscriver

Eventbus.register()

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    // 查找该订阅者需要接收事件的方法
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        // 主要是将 事件、事件类型、订阅者等进行存储,同时,接收 stick 事件,详细看后面源码。
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

找寻订阅方法 SubscriberMethodFinder.findSubscriberMethods

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
    // Eventbus 每次订阅时,会将订阅者为 key,订阅者接收事件的方法 list 为 value存储进 METHOD_CACHE 缓存中,如果有缓存,直接返回。
    List<SubscriberMethod> 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;
    }
}

注意上面忽略编译时注解那部分,由于如果使用编译时注解的文件,那么就没有继续分析下去的意义了,所以,这里不分析使用编译时注解的情况。那么,直接点进 findUsingReflection(subscriberClass)

通过反射,寻找接收消息的方法 SubscriberMethodFinder.findUsingReflection

private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
    // FindState 是用来存储找到的方法、订阅者类等的对象。
    FindState findState = prepareFindState();
    findState.initForSubscriber(subscriberClass);
    // 下面就是真正搜索的方法,包括订阅者父类的接收消息的方法,也一并会被找出来,当然,这个是可配置的。
    while (findState.clazz != null) {
        // 搜索接收消息的方法
        findUsingReflectionInSingleClass(findState);
        // 跳转到父类,继续搜索,直到父类为空为止。
        findState.moveToSuperclass();
    }
    // 返回搜索到的方法并清空 findState 的变量。
    return getMethodsAndRelease(findState);
}

SubscriberMethodFinder.findUsingReflectionInSingleClass

接下来就来看看真正执行反射的方法。

private void findUsingReflectionInSingleClass(FindState findState) {
    Method[] methods;
    try {
        // findState。clazz 就是订阅者或者订阅者的父类
        // 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();
        //method 必须为 public
        if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
            Class<?>[] parameterTypes = method.getParameterTypes();
            // 方法参数必须为一个
            if (parameterTypes.length == 1) {
                Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
                if (subscribeAnnotation != null) {
                    Class<?> eventType = parameterTypes[0];
                    // 检验是否可以添加,有两级校验,第一级是根据 eventType 为 key进行校验,第二级根据 method 以及 eventType 生成 key,再次进行校验,详细实现自行查看。
                    if (findState.checkAdd(method, eventType)) {
                        // 封装 SubscribeMethod,添加到 subscriberMethods 里面。
                        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");
        }
    }
}

上面的实现非常简单,相信没看源码之前你也能意淫出大概是长这样。主要就是找到接收消息的方法就进行校验,然后存储到 findState 里面的 subscriberMethods 里面。
这样,整个搜寻就完成了,再次回到 register 方法。

public void register(Object subscriber) {
    Class<?> subscriberClass = subscriber.getClass();
    // 查找该订阅者需要接收事件的方法
    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
    synchronized (this) {
        // 主要是将 事件、事件类型、订阅者等进行存储,同时,接收 stick 事件,详细看后面源码。
        for (SubscriberMethod subscriberMethod : subscriberMethods) {
            subscribe(subscriber, subscriberMethod);
        }
    }
}

点进 subscribe 方法

EventBus.subscribe

private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
    Class<?> eventType = subscriberMethod.eventType;
    // 将订阅者以及接收事件的方法封装成一个 subscription,为什么需要一个方法以及订阅者封装成的 subscription 对象呢?
    // 原因就是 EventBus 支持仅仅解绑订阅者中的某一个方法。
    Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
    // 根据事件类型取出所有的 subscription。subscrpiption。后面的判空以及赋值的不说了,太简单。
    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);
        }
    }

    // 这个循环主要是将优先级(priority) 高的放在 list 的前面。
    int size = subscriptions.size();
    for (int i = 0; i <= size; i++) {
        if (i == size || subscriberMethod.priority > subscriptions.get(i).subscriberMethod.priority) {
            subscriptions.add(i, newSubscription);
            break;
        }
    }

    List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
    if (subscribedEvents == null) {
        subscribedEvents = new ArrayList<>();
        typesBySubscriber.put(subscriber, subscribedEvents);
    }
    subscribedEvents.add(eventType);

    // 这里就是处理 stick 事件的了,这里的 stickEvents 是在 postStick 的时候进行赋值的。
    if (subscriberMethod.sticky) {
        if (eventInheritance) {
            // Existing sticky events of all subclasses of eventType have to be considered.
            // Note: Iterating over all events may be inefficient with lots of sticky events,
            // thus data structure should be changed to allow a more efficient lookup
            // (e.g. an additional map storing sub classes of super classes: Class -> List<Class>).
            Set<Map.Entry<Class<?>, Object>> entries = stickyEvents.entrySet();
            for (Map.Entry<Class<?>, Object> entry : entries) {
                Class<?> candidateEventType = entry.getKey();
                if (eventType.isAssignableFrom(candidateEventType)) {
                    Object stickyEvent = entry.getValue();
                    checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                }
            }
        } else {
            Object stickyEvent = stickyEvents.get(eventType);
            checkPostStickyEventToSubscription(newSubscription, stickyEvent);
        }
    }
}

整个订阅流程就看完了,订阅完之后要干嘛?发送事件啊。

事件的发送

这里直接看 postSticky,因为其内部也会调用 post 方法。

EventBus.postSticky()

public void postSticky(Object event) {
    synchronized (stickyEvents) {
        // 看到没,就是这里,把事件的类型为key,事件对象为 value 存储到map 里面。
        // 从这里也看出,如果 postStick 了两个相同类型的 event,则前一个会覆盖掉。
        stickyEvents.put(event.getClass(), event);
    }
    // Should be posted after it is putted, in case the subscriber wants to remove immediately
    post(event);
}

EventBus.post()

/** Posts the given event to the event bus. */
public void post(Object event) {
    //PostingThreadState 会使用 ThradLocal 根据线程拿到当前线程的PostingThreadState,了解过 handler 机制的同志应该知道。
    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;
        }
    }
}

EventBus.postSingleEvent

private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
    Class<?> eventClass = event.getClass();
    boolean subscriptionFound = false;
    if (eventInheritance) {
        // 根据事件类型,取出自身以及父类、接口所有的类型。
        List<Class<?>> eventTypes = lookupAllEventTypes(eventClass);
        int countTypes = eventTypes.size();
        for (int h = 0; h < countTypes; h++) {
            Class<?> clazz = eventTypes.get(h);
            // 执行发送,返回是否找到订阅者
            subscriptionFound |= postSingleEventForEventType(event, postingState, clazz);
        }
    } else {
        subscriptionFound = postSingleEventForEventType(event, postingState, eventClass);
    }
    if (!subscriptionFound) {
        if (logNoSubscriberMessages) {
            Log.d(TAG, "No subscribers registered for event " + eventClass);
        }
        if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                eventClass != SubscriberExceptionEvent.class) {
            post(new NoSubscriberEvent(this, event));
        }
    }
}

上面的方法会根据 eventInheritance 是否为 true 来决定需要发送给哪些订阅者。如果为true,则接收包括 event 自身,event 的父类以及接口类型的事件的订阅者,都会收到事件。

EventBus.postSingleEventForEventType()

private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
     CopyOnWriteArrayList<Subscription> subscriptions;
     synchronized (this) {
         subscriptions = subscriptionsByEventType.get(eventClass);
     }
     if (subscriptions != null && !subscriptions.isEmpty()) {
        // 取出订阅者并未 postingState 赋值。
         for (Subscription subscription : subscriptions) {
             postingState.event = event;
             postingState.subscription = subscription;
             boolean aborted = false;
             try {
                //根据subscription 接收事件的线程以及当前线程来发送事件。
                 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;
 }

EventBus.postToSubscription()

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    // 方法指定的接收事件的线程,直接放结论:上篇博客其实也有提到
    // 1.如果为 posting,则接收事件以及发送事件会在同一线程执行。
    // 2.如果为 mainThread,如果当前线程不是主线程,则会交给 mainThreadPoster 去执行,mainThreadPoster 是一个 handler,内部持有主线程的消息队列,前面有提到。
    // 3.如果为 background,如果当前是主线程,则交给 backgroundPoster 执行,进而交给 eventBus 的线程池执行,否则,将在同一线程执行。
    // 4.如果为 Async,则不管当前是啥线程,都交给 asyncPoster 执行,确保每一个任务都在不同的线程中。

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

上面,也就是关于对官方文档中线程分发的一个解释吧,有兴趣看实现的也可以去看,并不复杂。

总结

流程大概就是这样,分析完了 register 以及 post,其他的都不难分析了。上面一些存储事件以及订阅者的 map 或者是 list,虽然在我分析的源码中没什么卵用,但是你去看看解除注册的那些代码,就知道他的作用了。
其实 EventBus 的源码相对来说比较简单,我没看源码前也大概猜出这个流程,不过里面对并发的控制还是不错的,还是有值得我们学习的地方的。
至于编译注解,有兴趣的可以自己去看,我直接放上链接。EventBusAnnotationProcessor
其实我一直觉得分析源码这类博客,不必看太细,主要是看个大概,知道这东西干嘛用以及流程大概怎样就好,避免自己阅读源码的时候掉进坑里,不能抓住主要流程。然后自己再去看,就会少走许多弯路。
最后,拜拜。

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值