EventBus源码分析

本文详细剖析了EventBus的工作原理及源码实现,包括事件的注册、发布、取消注册等核心流程。通过阅读源码,深入理解EventBus的内部机制及其应用场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在进入EventBus源码分析之前,如果对EventBus的使用还不是很清楚的,可以参考上一篇文章EventBus使用
首先我们先通过一张简单的图来了解一下EventBus的工作原理:
EventBus工作原理图:
这里写图片描述
也可以看这张图:
这里写图片描述
当然作为一名Android开发人员,我们肯定是想更深入地了解EventBus是怎么工作的,所以探讨源码是必不可少的。所以我们将进行EventBus源码的解读,并了解其架构的实现和工作原理,并通过源码解读,更加深入的了解各种使用场景和事件类型,响应Mode。
EventBus 源码地址:https://github.com/greenrobot/EventBus.git
下载源码后,我们将其导入到Android Studio中,代码目录比较简单,如下图展示:

这里写图片描述

为了更好的了解和认识EventBus的代码结构和类关系,把代码导入到了PD中,生成了类关系图,如下图所示:

这里写图片描述

从上图可以看出,主要使用到的是EventBus.java主类,此类主要提供了一些接口的封装和逻辑处理,默认EventBus实例的创建和应用。下面我们来进入代码,根据源码看看EventBus是怎么走的。

EventBus的实例化:

 /** 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;
    }

    public static EventBusBuilder builder() {
        return new EventBusBuilder();
    }

    /** For unit test primarily. */
    public static void clearCaches() {
        SubscriberMethodFinder.clearCaches();
        eventTypesCache.clear();
    }

    /**
     * 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) {
        // 创建订阅事件类型HashMap,用于存储注册类中订阅的事件对应的所有方法,key为class即订阅类,value为CopyOnWriteArrayList<Subscription>,此列表记录了相同事件类型的所有订阅方法列表。
        subscriptionsByEventType = new HashMap<>();
        //创建typesBySubscriber,用于记录subscriber中已经注册的eventType类型情况
        typesBySubscriber = new HashMap<>();
        //创建stickyEvents,用于记录和检查发送sticky事件
        stickyEvents = new ConcurrentHashMap<>();
        //接下来是创建3中不同Mode的Poster
        mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
        backgroundPoster = new BackgroundPoster(this);
        asyncPoster = new AsyncPoster(this);
        indexCount = builder.subscriberInfoIndexes != null ? builder.subscriberInfoIndexes.size() : 0;
        //SubscriberMethodFinder的创建,用于遍历查找注册者类中的特殊名字方法,即订阅事件的回调函数。
        subscriberMethodFinder = new SubscriberMethodFinder(builder.subscriberInfoIndexes,
                builder.strictMethodVerification, builder.ignoreGeneratedIndex);
        //EventBus的常用参数配置,包括异常信息,log信息等
        logSubscriberExceptions = builder.logSubscriberExceptions;
        logNoSubscriberMessages = builder.logNoSubscriberMessages;
        sendSubscriberExceptionEvent = builder.sendSubscriberExceptionEvent;
        sendNoSubscriberEvent = builder.sendNoSubscriberEvent;
        throwSubscriberException = builder.throwSubscriberException;
        eventInheritance = builder.eventInheritance;
        executorService = builder.executorService;
    }

默认调用的EventBus是单例存在,如果想自定义创建更多的EventBus,可以通过EventBusBuilder进行创建,在

EventBus(EventBusBuilder builder)

中做了如下几件事,其实已经在代码中注释了:
1、创建订阅事件类型HashMap,用于存储注册类中订阅的事件对应的所有方法,key为class即订阅类,value为CopyOnWriteArrayList,此列表记录了相同事件类型的所有订阅方法列表。
其中CopyOnWriteArrayList是ArrayList的一种衍生类型,此类适用于多线程同时需要对list进行操作和遍历的场景,在add对象时会对原本list进行copy后再进行操作更新,防止出现java.util.ConcurrentModificationException错误。 Subscription是订阅者对象:

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

    @Override
    public boolean equals(Object other) {
        if (other instanceof Subscription) {
            Subscription otherSubscription = (Subscription) other;
            return subscriber == otherSubscription.subscriber
                    && subscriberMethod.equals(otherSubscription.subscriberMethod);
        } else {
            return false;
        }
    }

    @Override
    public int hashCode() {
        return subscriber.hashCode() + subscriberMethod.methodString.hashCode();
    }
}

订阅者对象中记录了对订阅者回调事件函数和订阅优先级的记录,用于订阅事件函数插入的排序。
2、 创建typesBySubscriber,用于记录subscriber中已经注册的eventType类型情况

3、 创建stickyEvents,用于记录和检查发送sticky事件

4、接下来是创建3中不同Mode的Poster:

 mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
 backgroundPoster = new BackgroundPoster(this);
 asyncPoster = new AsyncPoster(this);

5、 SubscriberMethodFinder的创建,用于遍历查找注册者类中的特殊名字方法,即订阅事件的回调函数。
6、EventBus的常用参数配置,包括异常信息,log信息等
接下来我们来看看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();
        //通过一个findSubscriberMethods方法找到了一个订阅者中的所有订阅方法,返回一个 List<SubscriberMethod>
        List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }
    }

    // Must be called in synchronized block
    private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
        //从订阅方法中拿到订阅事件的类型
        Class<?> eventType = subscriberMethod.eventType;
        //创建一个新的订阅
        Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
        //通过订阅事件类型,找到所有的订阅(Subscription),订阅中包含了订阅者,订阅方法
        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;
            }
        }
        //将这个订阅事件加入到订阅者的订阅事件列表中
        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();
                    if (eventType.isAssignableFrom(candidateEventType)) {
                        Object stickyEvent = entry.getValue();
                        checkPostStickyEventToSubscription(newSubscription, stickyEvent);
                    }
                }
            } else {
                Object stickyEvent = stickyEvents.get(eventType);
                checkPostStickyEventToSubscription(newSubscription, stickyEvent);
            }
        }
    }

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

从上述代码我们可以验证上一篇EventBus的使用中说的,注册只需要一行代码搞定:

EventBus.getDefault().register(this);

也就是默认把当前类注册到EventBus队列中,具体实现逻辑在这里可以看到:

List<SubscriberMethod> subscriberMethods =    subscriberMethodFinder.findSubscriberMethods(subscriberClass);
        synchronized (this) {
            for (SubscriberMethod subscriberMethod : subscriberMethods) {
                subscribe(subscriber, subscriberMethod);
            }
        }

当一个类需要往EventBus中注册自己时,通过Finder遍历类中以onEvent开头命名的函数,并把函数中第一个参数当做eventType,并过滤掉一些特殊的方法,把最后结果输出到subscriberMethods中,接着一个接一个得创建订阅,并add到上面描述的list中,为以后的事件发布做准备。也就是通过一个findSubscriberMethods方法找到了一个订阅者中的所有订阅方法,返回一个 List,进入到findSubscriberMethods看看如何实现的。

List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) {
        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;
        }
    }

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

 private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
        FindState findState = prepareFindState();
        findState.initForSubscriber(subscriberClass);
        while (findState.clazz != null) {
            findUsingReflectionInSingleClass(findState);
            findState.moveToSuperclass();
        }
        return getMethodsAndRelease(findState);
    }

    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();
            //判断订阅者是否是public的,并且是否有修饰符,看来订阅者只能是public的,并且不能被final,static等修饰
            if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
                //获得订阅函数的参数
                Class<?>[] parameterTypes = method.getParameterTypes();
                //看了参数的个数只能是1个
                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");
            }
        }
    }

我已经在源码上注释了,大家可以看看。
SubscriberMethodFinder中的findSubscriberMethods是主要实现遍历传入类中以onEvent开头函数列表的。从代码中我们可以看出它遍历时不需要关心的一些描述和包:

/*
 * In newer class files, compilers may add methods. Those are called bridge or synthetic methods.
 * EventBus must ignore both. There modifiers are not public but defined in the Java class file format:
 * http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-4.html#jvms-4.6-200-A.1
 */
private static final int BRIDGE = 0x40;
private static final int SYNTHETIC = 0x1000;

private static final int MODIFIERS_IGNORE = Modifier.ABSTRACT | Modifier.STATIC | BRIDGE | SYNTHETIC;
if (name.startsWith("java.") || name.startsWith("javax.") || name.startsWith("android.")) {
    // Skip system classes, this just degrades performance
    break;
}

EventBus的反注册流程:

  /** 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());
        }
    }

反注册流程,其实就是从订阅列表中移除订阅者的操作。
EventBus的post流程,事件发布流程:
在完成事件订阅后,基本上订阅操作就可以告一段落了,接下来就等着事件的发布,事件的发布主要是通过以下逻辑实现:

 /** Posts the given event to the event bus. */
    public void post(Object event) {
        //这个EventBus中只有一个,差不多是个单例吧
        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;
            }
        }
    }

这里主要是事件的发布,而事件的分发跟核心处理在postSingleEvent(Object event, PostingThreadState postingState)这个方法里面。

 private void postSingleEvent(Object event, PostingThreadState postingState) throws Error {
        Class<?> eventClass = event.getClass();
        boolean subscriptionFound = false;
        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);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                //如果没有订阅发现,那么会Post一个NoSubscriberEvent事件
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

这里做了一件事情,在前段描述的事件列表中,根据ecentType进行查找遍历是否有此事件类型的订阅者,如果有则post出去,如果没有,则post一个NoSubscriberEvent事件。

 private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
        CopyOnWriteArrayList<Subscription> subscriptions;
        synchronized (this) {
            //找到订阅事件对应的订阅,这个是通过register加入的
            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;
    }

当找到订阅事件时,我们需要遍历找出对应事件订阅的订阅者,再进行反射调用其处理函数进行通知处理。

private void postToSubscription(Subscription subscription, Object event, boolean isMainThread) {
    switch (subscription.subscriberMethod.threadMode) {
        case PostThread:
            invokeSubscriber(subscription, event);
            break;
        case MainThread:
            if (isMainThread) {
                invokeSubscriber(subscription, event);
            } else {
                mainThreadPoster.enqueue(subscription, event);
            }
            break;
        case BackgroundThread:
            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);
    }
}

现在讲解事件的几个Mode:
在EventBus中的观察者通常有四种订阅函数(就是某件事情发生被调用的方法)

1、onEvent

2、onEventMainThread

3、onEventBackground

4、onEventAsync

这四种订阅函数都是使用onEvent开头的,它们的功能稍有不同,在介绍不同之前先介绍两个概念:

告知观察者事件发生时通过EventBus.post函数实现,这个过程叫做事件的发布,观察者被告知事件发生叫做事件的接收,是通过下面的订阅函数实现的。

onEvent:如果使用onEvent作为订阅函数,那么该事件在哪个线程发布出来的,onEvent就会在这个线程中运行,也就是说发布事件和接收事件线程在同一个线程。使用这个方法时,在onEvent方法中不能执行耗时操作,如果执行耗时操作容易导致事件分发延迟。

onEventMainThread:如果使用onEventMainThread作为订阅函数,那么不论事件是在哪个线程中发布出来的,onEventMainThread都会在UI线程中执行,接收事件就会在UI线程中运行,这个在Android中是非常有用的,因为在Android中只能在UI线程中跟新UI,所以在onEvnetMainThread方法中是不能执行耗时操作的。

onEvnetBackground:如果使用onEventBackgrond作为订阅函数,那么如果事件是在UI线程中发布出来的,那么onEventBackground就会在子线程中运行,如果事件本来就是子线程中发布出来的,那么onEventBackground函数直接在该子线程中执行。

onEventAsync:使用这个函数作为订阅函数,那么无论事件在哪个线程发布,都会创建新的子线程在执行onEventAsync.

PostThread:默认模式,在 Post 操作的线程直接调用订阅者的事件响应方法,不论该线程什么线程。当该线程为主线程时,响应方法中不要有耗时操作,否则会发生anr。
MainThread:在主线程中执行响应,如果发布线程就是主线程,则直接调用订阅者的事件响应方法,否则通过主线程的 Handler post回主线程中调用订阅者的事件响应方法。
BackgroundThread:在后台线程中执行响应方法。如果发布线程非主线程,则直接调用订阅者的事件响应函数,否则启动EventBus中唯一的后台线程去处理。由于后台线程是唯一的,当事件超过一个的时候,它们会被放在队列中依次执行,请不要把耗时操作放此进行,否则会阻塞后台队列的依次执行。
Async:使用一个空闲线程来处理。和上面不同的是,这里的所有线程是相互独立的,不会出现卡线程的问题。
至于这里调用订阅者的事件响应方法都是利用了反射原理,主要的创建,注册,订阅,发布和发注册流程就是以上的源码部分

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值