Android EventBus源码解析

    xiaoxiao2023-11-22  169

    1 EventBus的使用

    1.1 发送事件

    EventBus.getDefault().post(MessageEvent);

    1.2 接收事件

    EventBus.getDefault().register(activity or fragment); EventBus.getDefault().unregister(activity or fragment); @Subscribe(threadMode = ThreadMode.MAIN) public void onMessageEvent(MessageEvent event) {}

    2 EventBus事件发布解析

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

    EventBus.getDefault() 创建了一个单例的EventBus,再看下EventBus的构造函数:

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

    EventBus是通过 EventBusBuilder 进行初始化。

    接下来是事件的发布:

    /** Posts the given event to the event bus. */ public void post(Object event) { // currentPostingThreadState是一个ThreadLocal // 默认返回一个PostingThreadState 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; } } } // 事件发送封装类 /** For ThreadLocal, much faster to set (and get multiple values). */ final static class PostingThreadState { final List<Object> eventQueue = new ArrayList<>(); boolean isPosting; boolean isMainThread; Subscription subscription; Object event; boolean canceled; } 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); } ... } private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) { CopyOnWriteArrayList<Subscription> subscriptions; synchronized (this) { // Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType // 根据要发送的event类型获取订阅了该event类型的订阅者 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 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); } } void invokeSubscriber(Subscription subscription, Object event) { try { // 最终通过订阅者中使用scope @Subscribe注解的方法进行反射 subscription.subscriberMethod.method.invoke(subscription.subscriber, event); } catch (InvocationTargetException e) { handleSubscriberException(subscription, event, e.getCause()); } catch (IllegalAccessException e) { throw new IllegalStateException("Unexpected exception", e); } }

    事件发送的方法流动走向:

    post(event) -> postSingleEvent(event, postingState) -> postSingleEventForEventType(event, postingState, eventClass) -> postToSubscription(subscription, event, postingState.isMainThread) -> invokeSubscriber(subscription, event) -> subscription.subscriberMethod.method.invoke(subcritpion.subscriber, event)

    从上面的流动走向可以看出,最终的事件发送其实是通过反射的方式实现。

    上面有两个比较重要的model:

    PostingThreadState:用来存储即将发送的事件、事件队列、订阅者

    Subscription:订阅者,一般是Activity或Fragment

    总结下EventBus发送事件的流程:

    传递要发送的事件event,将事件添加进事件队列,开始发布事件

    根据event事件对象类型获取订阅者列表,循环订阅者列表

    拥有订阅者(内部有@Subscribe注解绑定的方法字段)、待发布事件event,反射订阅者绑定的方法完成事件发送

    2 EventBus事件订阅解析

    2.1 EventBus.register(object)

    // subscriber一般是Activity或Fragment public void register(Object subscriber) { Class<?> subscriberClass = subscriber.getClass(); // 根据订阅者类获取类中使用scope @Subscribe注解绑定的方法,这里委托给subscriberMethodFinder查找注解方法 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); // Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType // 根据要发送的event类型获取订阅了该event类型的订阅者,添加订阅者 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; } } // Map<Object, List<Class<?>>> typesBySubscriber // 根据订阅者类获取事件event列表 List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber); if (subscribedEvents == null) { subscribedEvents = new ArrayList<>(); typesBySubscriber.put(subscriber, subscribedEvents); } subscribedEvents.add(eventType); ... }

    事件订阅只做了三件事:

    根据订阅者类查找类中的方法,找到被scope @Subscribe注解的方法

    创建一个新的订阅者,以事件event类为key,订阅者类为value存储到一个Map中

    以订阅者类为key,事件event类为value存储到一个Map中,用于解注册

    2.2 SubscriberMethodFinder查找订阅者中订阅事件的方法

    在订阅者 EventBus.getDefault().register(object) 时,执行了一步查找订阅事件的方法:

    List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);

    详细了解下这个方法的操作过程:

    List<SubscriberMethod> findSubscriberMethods(Class<?> subscriberClass) { // Map<Class<?>, List<SubscriberMethod>> METHOD_CACHE = new ConcurrentHashMap<>(); // 根据订阅者类为key返回订阅方法列表,属于缓存 List<SubscriberMethod> subscriberMethods = METHOD_CACHE.get(subscriberClass); if (subscriberMethods != null) { return subscriberMethods; } if (ignoreGeneratedIndex) { subscriberMethods = findUsingReflection(subscriberClass); } else { subscriberMethods = findUsingInfo(subscriberClass); } // 如果找不到使用@Subscribe注解的方法,抛出异常 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> findUsingReflection(Class<?> subscriberClass) { // 初始化订阅方法查找信息 FindState findState = prepareFindState(); findState.initForSubscriber(subscriberClass); while (findState.clazz != null) { // 开始查找订阅者类中的订阅方法 findUsingReflectionInSingleClass(findState); findState.moveToSuperclass(); } return getMethodsAndRelease(findState); } private FindState prepareFindState() { // private static final int POOL_SIZE = 4; // FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE]; // FindState对象池,FindState对象是订阅方法查找的封装类,存储着订阅者的订阅方法、订阅方法类型等数据 synchronized (FIND_STATE_POOL) { for (int i = 0; i < POOL_SIZE; i++) { FindState state = FIND_STATE_POOL[i]; if (state != null) { FIND_STATE_POOL[i] = null; return state; } } } return new FindState(); } // FindState.inintForSubscribe() // 将订阅者类存储起来 void initForSubscriber(Class<?> subscriberClass) { this.subscriberClass = clazz = subscriberClass; skipSuperClasses = false; subscriberInfo = null; } private void findUsingReflectionInSingleClass(FindState findState) { Method[] methods; try { // This is faster than getMethods, especially when subscribers are fat classes like Activities // findState.clazz是订阅者类,一般是Activity或Fragment,通过反射拿到类中的所有方法 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; } // 开始遍历订阅者类的所有方法,获取使用了@Subscribe注解的方法 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); // 找到了用@Subcribe注解的方法,添加到订阅方法列表中最终返回 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"); } } }

    查找订阅者类中订阅方法的方法流动走向:

    findSubscriberMethods(subscriberClass) -> findUsingReflection(subscriberClass) -> findUsingReflectionInSingleClass(FindState)

    从上面的方法流动方向可以知道,查找订阅方法同样是使用反射的方式实现。

    总结下查找订阅方法的流程:

    从方法池中根据订阅者类获取订阅方法列表,如果有则直接返回

    从对象池中获取查找订阅方法和订阅者的封装对象FindState,通过反射的方式查找订阅者类中的所有方法,找到方法public公开且使用@Subscribe注解的方法,添加进订阅方法列表中

    释放FindState对象,返回订阅方法列表

    2.3 EventBus.unregister(object)

    /** Unregisters the given subscriber from all event classes. */ public synchronized void unregister(Object subscriber) { // Map<Object, List<Class<?>>> typesBySubscriber // 根据订阅者类获取事件event列表 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()); } } /** Only updates subscriptionsByEventType, not typesBySubscriber! Caller must update typesBySubscriber. */ private void unsubscribeByEventType(Object subscriber, Class<?> eventType) { // Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType // 根据事件event类获取订阅者列表,移除订阅者 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--; } } } }

    解注册比较简单,就是把订阅时添加的订阅者移除出列表。

    3 @Subscribe注解处理器

    EventBus也使用了Annotation Processor支持 @Subscribe 注解和自动生成代码,具体的类为 EventBusAnnotationProcessor,详细的Annotation Processor可以看我另外一篇文章:https://blog.csdn.net/qq_31339141/article/details/93374206

    最新回复(0)