EventBus使用以及源码处理

  1. 使用EventBus

这部分之前学习过了,这里贴了我之前写的博客

  1. EvetBus源码解析

在这里插入图片描述

  1. EventBus的构建方法

不管我们进行什么操作,post或者register,都需要使用EventBus.getDefault()来获取实例,那么首先看一下这个方法内部是如何实现的
    public static EventBus getDefault() {
        if (defaultInstance == null) {
            synchronized (EventBus.class) {
                if (defaultInstance == null) {
                    defaultInstance = new EventBus();
                }
            }
        }
        return defaultInstance;
    }

这里是一个单例模式,使用双重检查方法,现在进一步查看EventBus的构造方法

public EventBus() {
    this(DEFAULT_BUILDER);
}

private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();

EventBus(EventBusBuilder builder) {
    logger = builder.getLogger();
    subscriptionsByEventType = new HashMap<>();
    typesBySubscriber = new HashMap<>();
    stickyEvents = new ConcurrentHashMap<>();
    mainThreadSupport = builder.getMainThreadSupport();
    mainThreadPoster = mainThreadSupport != null ? mainThreadSupport.createPoster(this) : null;
    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;
}

这里构建了一个EventBusBuilder来实现对EventBus的配置,这里使用了建造者模式

  1. EventBus的订阅者注册

获得EventBus对象之后需要使用register方法来进行注册,现在看一下这个方法

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

首先它获取了订阅者的类对象,然后利用findSubscriberMethods方法获取了所有的订阅者方法(即那些应该被注册以响应特定事件的方法)的对象。最后在同步代码块中使用增强for遍历了每一个订阅者方法,这里有俩个方法需要注意一下分别是findSubscriberMethods和subscribe

查找订阅者的订阅方法

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

从缓存中查找是否有订阅方法的集合,如果找到了就立马返回。

如果缓存中没有,则根据ignoreGeneratedIndex属性的值来选择采用何种方法查找订阅方法的集合。ignoreGeneratedIndex属性表示是否忽略注解器生成的MyEventBusIndex。如何生成ignoreGeneratedIndex属性表示是MyEventBusIndex类以及它的使用,HignoreGeneratedIndex的默认值是false,可以通过EventBusBuilder来设置它的值。

然后找到订阅方法的集合后,判断她是否是空,如果不是,放入缓存,以免下次继续查找。我们在项目中经常通过EventBus单例模式来获取默认的EventBus对象,也就是ignoreGeneratedIndex为false的情况,这种情况下的findUsingInfo方法:

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

getSubscriberInfo方法来获取订阅者信息。在我们开始查找订阅方法的时候并没有忽略注解器为我们门生成的索引MyEventBusIndex。如果我们通过EventBusBuilder配置了MyEventBusIndex,便会获取subscriberInfo。

subscriberInfo的getSubscriberMethods方法便可以得到订阅方法的相关信息。如果没有配置MyEventBusIndex,便会执行findUsingReflectionInSingleClass方法,将订阅方法保存到findState中。

最后再通过getMethodsAndRelease方法对findState做回收处理并返回订阅方法的List集合。默认情况下是没有配置MyEventBusIndex的,

现在查看一下findUsingReflectionInSingleClass方法的执行过程,如下所示:

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

这里的核心代码是 findUsingReflectionInSingleClass

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
        try {
            methods = findState.clazz.getMethods();
        } catch (LinkageError error) { // super class of NoClassDefFoundError to be a bit more broad...
            String msg = "Could not inspect methods of " + findState.clazz.getName();
            if (ignoreGeneratedIndex) {
                msg += ". Please consider using EventBus annotation processor to avoid reflection.";
            } else {
                msg += ". Please make this class visible to EventBus annotation processor to avoid reflection.";
            }
            throw new EventBusException(msg, error);
        }
        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");
        }
    }
}

getDeclaredMethods()通过反射来获取订阅者中所有的方法,并根据方法的类型、参数和注解来找到订阅方法。找到订阅方法后将订阅方法的相关信息保存到findState中。

订阅者的注册过程

前面是对订阅方法的查找,现在需要对已经查找到方法进行注册,这里使用了subscribe方法

subscribe:

    /**
     * 订阅指定的事件给订阅者。
     * 
     * @param subscriber 订阅者对象,即要接收事件的对象。
     * @param subscriberMethod 订阅方法,包含订阅者订阅事件的详细信息,如事件类型和优先级。
     */
    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;
            }
        }

        // 记录订阅者订阅的事件类型
        List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
        if (subscribedEvents == null) {
            subscribedEvents = new ArrayList<>();
            typesBySubscriber.put(subscriber, subscribedEvents);
        }
        subscribedEvents.add(eventType);

        // 如果是粘性事件,则检查并发布相应的粘性事件
        if (subscriberMethod.sticky) {
            if (eventInheritance) {
                // 处理事件继承情况下的粘性事件发布
                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);
            }
        }
    }

首先会根据subscriber(订阅者)和subscriberMethod(订阅方法)创建一个Subscription(订阅对象)。

然后根据eventType(事件类型)获取Subscriptions(订阅对象集合)。如果Subscriptions为null则重新创建,并将Subscriptions根据event保存在TypesubscriptionsByEventType(Map集合)。

按照订阅方法的优先级插入到订阅对象集合中,完成订阅方法的注册。

通过subscriber获取subscribedEvents(事件类型集合)如果subscribedEvents为null则重新创建,将eventType添加到subscribedEvents并根据中,subscriber将subscribedEvents存储在typeesBySubscriber(Map集合)。如果是黏性事件,则从stickyEvents事件保存队列中取出该事件类型的事件发送给当前订阅者。

总结一下,subscribe方法主要就是做了两件事:一件事是将Subscriptions根据eventType封装到subscriptionsventType中,将subscribedEvents根据subscriber封装到typesBySubscriber中;第二件事就是对黏性事件进行处理。

  1. 事件的发送

就是post方法

    /**
     * 将事件对象发布到事件总线。
     * 此方法会将事件添加到当前线程的事件队列中,并尝试立即分发此事件,如果当前线程不是事件总线的分发线程,则会标记为异步分发。
     * 如果事件队列中已经有事件正在等待分发,则会将新事件添加到队列末尾等待分发。
     * 
     * @param event 要发布到事件总线的事件对象。
     */
    public void post(Object event) {
        // 获取当前线程的状态,用于管理事件队列和线程状态
        PostingThreadState postingState = currentPostingThreadState.get();
        List<Object> eventQueue = postingState.eventQueue;
        // 将事件添加到当前线程的事件队列
        eventQueue.add(event);

        // 如果当前线程不是正在发布状态,则设置为发布状态,并尝试分发所有等待的事件
        if (!postingState.isPosting) {
            postingState.isMainThread = isMainThread();
            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对象中取出事件队列,然后再将当前的事件插入事件队列。最后将队列中的事件依次交由postSingleEvent方法进行处理,并移除该事件。之后查看postSingleEvent方法里做了什么:

    /**
     * 针对单个事件进行发布,尝试将其分发给所有订阅了该事件类型的订阅者。
     * 如果没有找到任何订阅者,将根据配置记录日志或发布一个无订阅者事件。
     * 
     * @param event 要发布的事件对象。
     * @param postingState 当前发布状态,包含线程安全等状态信息。
     * @throws Error 如果发布过程中遇到严重错误。
     */
    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) {
                logger.log(Level.FINE, "No subscribers registered for event " + eventClass);
            }
            if (sendNoSubscriberEvent && eventClass != NoSubscriberEvent.class &&
                    eventClass != SubscriberExceptionEvent.class) {
                post(new NoSubscriberEvent(this, event));
            }
        }
    }

首先判断是否向上查找事件的父类,如果确定查找通过 lookupAllEventTypes方法找到所有的父类事件,然后将其存入List集合,通过postSingleEventForEventType方法来具体处理事件

    /**
     * 尝试为特定事件类型发布单个事件。
     * <p>
     * 函数首先通过事件类型从订阅列表中获取所有订阅者,然后遍历这些订阅者,尝试为每个订阅者发布事件。
     * 如果发布过程中遇到订阅者取消订阅的情况,则停止进一步的发布。
     * </p>
     * @param event 要发布的事件对象。
     * @param postingState 当前发布状态,包含是否在主线程发布、是否已取消等信息。
     * @param eventClass 事件对象的类,用于查找订阅者。
     * @return 如果成功发布至少一个事件给一个订阅者,则返回true;如果没有订阅者或发布被取消,则返回false。
     */
    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;
                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;
    }

同步取出该事件对应的Subscriptions(订阅对象集合)。

遍历Subscriptions,将事件event和对应的Subscription(订阅对象)传递给postingState并调用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 MAIN_ORDERED:
            if (mainThreadPoster != null) {
                mainThreadPoster.enqueue(subscription, event);
            } else {
                // temporary: technically not correct as poster not decoupled from subscriber
                invokeSubscriber(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);
    }
}

这里的代码就比较明了了,取出订阅方法的线程模式,然后根据不同的线程模式处理,如果是MAIN,则提交事件的线程是主线程,通过反射运行订阅的方法,如果不是就将其添加到主线程队列中,这里的mainThreadPoster是HandlerPoster,继承自Handler,通过Handler切换到主线程执行

  1. 订阅者取消注册

取消注册使用unregister方法

    /**
     * 注销给定的订阅者,将其从订阅列表中移除。
     * @param subscriber 要注销的订阅者对象。
     */
    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 {
            // 如果订阅者未注册过,则记录警告信息
            logger.log(Level.WARNING, "Subscriber to unregister was not registered before: " + subscriber.getClass());
        }
    }

我们在订阅者注册的过程中讲过typesBySubscriber,它是一个Map集合。在上面代码处通过subscriber找到subscribedTypes(事件类型集合)。在将subscriber对应的eventType从typesBySubscriber中移除。处遍历subscribedTypes,并调用unsubscribeByEventType方法:

    /**
     * 根据事件类型取消订阅。
     * 该方法遍历与特定事件类型关联的订阅列表,找到与给定订阅者匹配的订阅,并将其标记为非活动状态,然后从列表中移除。
     * 
     * @param subscriber 需要取消订阅的订阅者对象。
     * @param eventType 需要取消订阅的事件类型。
     */
    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--;
                }
            }
        }
    }

在上面代码通过eventType来得到对应的Subscriptions(订阅对象集合),并在for循环中判断如果Subscription(订阅对象)的subscriber(订阅者)属性等于传进来的subscriber,则从Subscriptions中移除该Subscription。

  • 14
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值