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,反射订阅者绑定的方法完成事件发送
事件订阅只做了三件事:
根据订阅者类查找类中的方法,找到被scope @Subscribe注解的方法
创建一个新的订阅者,以事件event类为key,订阅者类为value存储到一个Map中
以订阅者类为key,事件event类为value存储到一个Map中,用于解注册
在订阅者 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对象,返回订阅方法列表
解注册比较简单,就是把订阅时添加的订阅者移除出列表。
EventBus也使用了Annotation Processor支持 @Subscribe 注解和自动生成代码,具体的类为 EventBusAnnotationProcessor,详细的Annotation Processor可以看我另外一篇文章:https://blog.csdn.net/qq_31339141/article/details/93374206