EventBus 是一个 Android 事件发布/订阅框架,解耦代码利器。如此优秀的库,它的内部是如何工作的?
整体的架构可以看官方给的这张图,Event 通过 EventBus 中转分发到对应的订阅者(Sucscriber)。
初始化
从 Eventbus.getDeafult()
着手:
public static EventBus getDefault() {
if (defaultInstance == null) {
synchronized (EventBus.class) {
if (defaultInstance == null) {
defaultInstance = new EventBus();
}
}
}
return defaultInstance;
}
复制代码
getDefault()
是一个 DoudleCheckLock 单例。看看它的构造方法:
public EventBus() {
this(DEFAULT_BUILDER);
}
EventBus(EventBusBuilder builder) {
// private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// key:订阅的事件,value:订阅者的集合
// 订阅这个事件的所有订阅者集合
subscriptionsByEventType = new HashMap<>();
typesBySubscriber = new HashMap<>();
stickyEvents = new ConcurrentHashMap<>();
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;
executorService = builder.executorService;
}
private static final EventBusBuilder DEFAULT_BUILDER = new EventBusBuilder();
复制代码
这里传入了一个默认的 EventBusBuilder 对象,这里是常见的 Builder 模式。初始化了一堆 map 和很多变量,这些 map 和变量的意思其实现在可以不用太多关注,之后遇到再回来查看是什么含义,这样比较有针对性。
注册
public void register(Object subscriber) {
Class<?> subscriberClass = subscriber.getClass();
// 根据订阅者(Subscriber)去找到订阅者订阅的所有的方法
// SubscriberMethodFinder 是一个封装找订阅者的方法的辅助类
List<SubscriberMethod> subscriberMethods = subscriberMethodFinder.findSubscriberMethods(subscriberClass);
synchronized (this) {
// 遍历订阅所有的方法
for (SubscriberMethod subscriberMethod : subscriberMethods) {
subscribe(subscriber, subscriberMethod);
}
}
}
复制代码
很显然这里需要看下 findSubscriberMethods()
和 subscribe()
里面具体做了什么。
SubscriberMethodFinder#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);
}
// 订阅者不能一个方法都不订阅,否则这里就会报错,
// 我们封装在父类 Activity 时需要添加一个空的 `onEmpty()` 方法
if (subscriberMethods.isEmpty()) {
throw new EventBusException("Subscriber " + subscriberClass
+ " and its super classes have no public methods with the @Subscribe annotation");
} else {
// 存入缓存
// key: 订阅者(Subscriber), value: 订阅者订阅的方法集合
METHOD_CACHE.put(subscriberClass, subscriberMethods);
return subscriberMethods;
}
}
复制代码
这里暂停一下看一下 ignoreGeneratedIndex
,通过判断它来确定是使用 findUsingReflection()
即反射来找订阅方法,还是使用 findUsingInfo()
来找。
这里需要说明一下: EventBus 3.0 加入一个新特性 Subscriber Index。它可以加快订阅的速度,官方推荐使用,提高性能。它内部就是通过 apt 将所有被订阅的方法融合生成一个 Index 索引类,这样不需要反射,官方称效率比之前提高了近三倍。关于 Subscriber Index 后面再独立看,这里先看反射的方法。
SubscriberMethodFinder#findUsingReflection():
private List<SubscriberMethod> findUsingReflection(Class<?> subscriberClass) {
// 准备 findState
// 这里的 FindState 也是个辅助内部类,用来检查和保存以及回收订阅方法。
FindState findState = prepareFindState();
// 初始化
findState.initForSubscriber(subscriberClass);
while (findState.clazz != null) {
// 根据 findstate 找方法
findUsingReflectionInSingleClass(findState);
// 将 clazz 赋值为订阅者的父类 clazz,来查找父类的订阅方法
findState.moveToSuperclass();
}
return getMethodsAndRelease(findState);
}
复制代码
// 初始化了一个数量为 4 的 FindState 数组,缓存 findstate 对象。
private static final int POOL_SIZE = 4;
private static final FindState[] FIND_STATE_POOL = new FindState[POOL_SIZE];
private FindState prepareFindState() {
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();
}
复制代码
通过反射查找订阅方法的逻辑在这:
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();
if ((modifiers & Modifier.PUBLIC) != 0 && (modifiers & MODIFIERS_IGNORE) == 0) {
Class<?>[] parameterTypes = method.getParameterTypes();
// 订阅方法只能有一个参数
if (parameterTypes.length == 1) {
// 获取 @Subscribe 注解
Subscribe subscribeAnnotation = method.getAnnotation(Subscribe.class);
if (subscribeAnnotation != null) {
Class<?> eventType = parameterTypes[0];
// 检查方法和参数,方法不能一样
if (findState.checkAdd(method, eventType)) {
// 获取注解中的线程参数
ThreadMode threadMode = subscribeAnnotation.threadMode();
// 将注解方法添加进 findState 的方法集合中
// 这里创建了一个 SubscriberMethod 对象,它里面包含了订阅方法的所有信息:
// 方法、事件参数类型、优先级、是否是粘性
findState.subscriberMethods.add(new SubscriberMethod(method, eventType, threadMode,
subscribeAnnotation.priority(), subscribeAnnotation.sticky()));
}
}
}
// ...省略检查的代码
}
}
}
public SubscriberMethod(Method method, Class<?> eventType, ThreadMode threadMode, int priority, boolean sticky) {
this.method = method;
this.threadMode = threadMode;
this.eventType = eventType;
this.priority = priority;
this.sticky = sticky;
}
复制代码
最后将 findState 中的订阅方法取出并返回:
private List<SubscriberMethod> getMethodsAndRelease(FindState findState) {
// 将 findState 的方法集合取出来,然后回收 findState
List<SubscriberMethod> subscriberMethods = new ArrayList<>(findState.subscriberMethods);
findState.recycle();
synchronized (FIND_STATE_POOL) {
// 将 findState 存入缓存
for (int i = 0; i < POOL_SIZE; i++) {
if (FIND_STATE_POOL[i] == null) {
FIND_STATE_POOL[i] = findState;
break;
}
}
}
return subscriberMethods;
}
复制代码
下面接着看 subscribe()
:
// Must be called in synchronized block
private void subscribe(Object subscriber, SubscriberMethod subscriberMethod) {
// 获取订阅方法中的参数类型即订阅事件。就是我们自己定义的实体类 XXXEvent
Class<?> eventType = subscriberMethod.eventType;
// 将订阅者和订阅方法封装成一个新的订阅对象
Subscription newSubscription = new Subscription(subscriber, subscriberMethod);
// private final Map<Class<?>, CopyOnWriteArrayList<Subscription>> subscriptionsByEventType;
// 将订阅对象存入一个 hashMap,key: 订阅事件, value: 订阅对象集合
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;
}
}
// private final Map<Object, List<Class<?>>> typesBySubscriber;
// 这里将订阅者订阅的所有订阅事件存在 map 中,key: 订阅者,value:订阅事件的集合
List<Class<?>> subscribedEvents = typesBySubscriber.get(subscriber);
if (subscribedEvents == null) {
subscribedEvents = new ArrayList<>();
typesBySubscriber.put(subscriber, subscribedEvents);
}
// 将订阅事件加入集合
subscribedEvents.add(eventType);
// 如果订阅的方法是粘性事件
if (subscriberMethod.sticky) {
// eventInheritance 表示一个订阅事件的子类是否也可以响应订阅者,
// 如需响应就必须遍历出所有的事件将其 post 给 Subscription(订阅对象),即立即分发给订阅对象。
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);
}
}
}
复制代码
到这里注册过程就结束了。
这个流程如图所示:
分发
/** Posts the given event to the event bus. */
public void post(Object event) {
// private final ThreadLocal<PostingThreadState> currentPostingThreadState
// 这里的 currentPostingThreadState 是一个存储了 PostingThreadState 的 threadLocal
// PostingThreadState 中存储了当前线程的订阅信息:订阅事件队列、是否正在分发、是否是主线程等等。
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;
}
}
}
/** 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;
}
复制代码
ThreadLocal 是一个线程内部的数据存储类,通过它可以在指定的线程中存储数据,而这段数据是不会与其他线程共享的。其内部原理是通过生成一个它包裹的泛型对象的数组,在不同的线程会有不同的数组索引值,通过这样就可以做到每个线程通过 get() 方法获取的时候,取到的只能是自己线程所对应的数据。
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);
//只要右边有一个为 true,subscriptionFound 就为 true
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));
}
}
}
复制代码
postSingleEvent()
中调用postSingleEventForEventType()
检查是否有订阅者订阅了该事件,如果没有订阅者就发送一条 NoSubscriberEvent
事件,表示没有订阅者订阅。
private boolean postSingleEventForEventType(Object event, PostingThreadState postingState, Class<?> eventClass) {
CopyOnWriteArrayList<Subscription> subscriptions;
synchronized (this) {
// 获取以订阅事件为key存储的 订阅对象集合。
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;
}
复制代码
postSingleEventForEventType()
做的事情就是从 map 中取出订阅了当前事件的订阅者信息的集合。把事件分发给这些订阅者,通知他们执行订阅方法。
下面看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 BACKGROUND:
if (isMainThread) {
// 在主线程的话就切换到 background 线程
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);
}
}
复制代码
上述代码对调用方法的 threadMode
进行了分流处理。
首先来了解一下 EventBus 的线程切换。EventBus 的线程有 4 种可选:
- POSTING
发送事件在哪个线程,接收事件就在哪个线程。默认是这种模式,这种模式性能开销最小,因为它不用做线程切换,对于耗时很短的任务应该优先使用这种模式。
- MAIN
接收事件时,切换到 Android 的主线程。如果发送事件也是在主线程,就等同于 POSTING 模式了。
- BACKGROUND
接收事件时,切换到一个子线程,它和主线程一样,是一个单线程,不能做耗时任务。只有当发送线程在主线程时,它才会切换。否则等同于 POSTING 模式,在哪个线程发送还在哪个线程接收。当事件超过一个的时候,它们会被放在队列中依次执行。
- ASYNC
不论任何时候,每次接收事件时,都新开一个独立的新线程。适用于一些耗时操作。EventBus 内部会通过线程池来管理这些线程。
这 4 种模式有各自的处理方式,直接看代码就能看出来。这里我们重点看一下 MAIN、BACKGROUND、ASYNC 的处理。
对应由这三位处理:
private final HandlerPoster mainThreadPoster;
private final BackgroundPoster backgroundPoster;
private final AsyncPoster asyncPoster;
复制代码
HandlerPoster
mainThreadPoster = new HandlerPoster(this, Looper.getMainLooper(), 10);
final class HandlerPoster extends Handler {
// PendingPostQueue 是内部存储了 PendingPost 的链表队列,PendingPost 内部存储了分发事件的所有信息。
private final PendingPostQueue queue;
// 处理订阅方法的最大耗时,默认是 10 ms
private final int maxMillisInsideHandleMessage;
private final EventBus eventBus;
// 标记是否正在处理消息
private boolean handlerActive;
HandlerPoster(EventBus eventBus, Looper looper, int maxMillisInsideHandleMessage) {
super(looper);
this.eventBus = eventBus;
this.maxMillisInsideHandleMessage = maxMillisInsideHandleMessage;
queue = new PendingPostQueue();
}
void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
// 将这个 pendingPost 插入到链表的尾部
queue.enqueue(pendingPost);
if (!handlerActive) {
handlerActive = true;
// 发一个消息出去
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
}
}
}
@Override
public void handleMessage(Message msg) {
boolean rescheduled = false;
try {
long started = SystemClock.uptimeMillis();
while (true) {
// 从链表的头部开始取数据
PendingPost pendingPost = queue.poll();
if (pendingPost == null) {
// 如果链表头部是空的,就再试一次,还为空就直接返回
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
handlerActive = false;
return;
}
}
}
// 调用订阅方法
eventBus.invokeSubscriber(pendingPost);
long timeInMethod = SystemClock.uptimeMillis() - started;
// 如果处理方法的耗时超过了最大耗时就将此事件重新发送
if (timeInMethod >= maxMillisInsideHandleMessage) {
if (!sendMessage(obtainMessage())) {
throw new EventBusException("Could not send handler message");
}
rescheduled = true;
return;
}
}
} finally {
handlerActive = rescheduled;
}
}
}
复制代码
HandlerPoster 是一个 Handler,内部将订阅信息(subscription) 和 订阅事件(event)封装成一个单链表队列。将新来的事件插入到队尾,每次分发事件直接调用sendMessage
发送一个空消息。处理的时候按顺序从链表头部开始处理,最终通过反射调用订阅方法。
BackgroundPoster
BackgroundPoster 是一个 Runnable。
和上面的 HandlerPoster
一样把事件插进链表的尾部。
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
synchronized (this) {
// 插入链表的尾部
queue.enqueue(pendingPost);
// executorRunning 标记当前线程是否正在执行任务
if (!executorRunning) {
executorRunning = true;
// private final static ExecutorService DEFAULT_EXECUTOR_SERVICE = Executors.newCachedThreadPool();
// 这里的线程执行者就是默认的 newCachedThreadPool
eventBus.getExecutorService().execute(this);
}
}
}
复制代码
执行部分和主线程一样,最终都是调用了 eventBus.invokeSubscriber(pendingPost);
,用反射调用订阅方法。
@Override
public void run() {
try {
try {
while (true) {
// 取出头部的数据,如果头部为空就过 1s 后再取。
PendingPost pendingPost = queue.poll(1000);
if (pendingPost == null) {
synchronized (this) {
// Check again, this time in synchronized
pendingPost = queue.poll();
if (pendingPost == null) {
executorRunning = false;
return;
}
}
}
eventBus.invokeSubscriber(pendingPost);
}
} catch (InterruptedException e) {
Log.w("Event", Thread.currentThread().getName() + " was interruppted", e);
}
} finally {
executorRunning = false;
}
}
复制代码
AsyncPoster
AsyncPoster 也是一个 Runnable,和 BackgroundPoster 不同它内部并没有标记线程是否在处理任务,它不会等前一个事件处理结束,而是直接新建一个新线程去处理,最终也是走向反射调用订阅方法。
class AsyncPoster implements Runnable {
private final PendingPostQueue queue;
private final EventBus eventBus;
AsyncPoster(EventBus eventBus) {
this.eventBus = eventBus;
queue = new PendingPostQueue();
}
public void enqueue(Subscription subscription, Object event) {
PendingPost pendingPost = PendingPost.obtainPendingPost(subscription, event);
queue.enqueue(pendingPost);
eventBus.getExecutorService().execute(this);
}
@Override
public void run() {
PendingPost pendingPost = queue.poll();
if(pendingPost == null) {
throw new IllegalStateException("No pending post available");
}
eventBus.invokeSubscriber(pendingPost);
}
}
复制代码
分发的过程如下图所示:
反注册
/** 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());
}
}
复制代码
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--;
}
}
}
}
复制代码
反注册就非常简单了,如上所示,先找出当前订阅者订阅的所有方法,遍历每个方法的订阅者集合,将当前订阅者从集合中删除。
Subscriber Index
开启索引需要使用 EventBus 注解解析器。
需要在 build.gradle 中配置:
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
// 配置代码生成的路径
arguments = [ eventBusIndex : 'com.example.myapp.MyEventBusIndex' ]
}
}
}
}
compile 'org.greenrobot:eventbus:3.0.0'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
复制代码
重新 build 之后会在 app/build/generated/source/apt 路径下生成一个文件。
public class ZZREventBusIndex implements SubscriberInfoIndex {
private static final Map<Class<?>, SubscriberInfo> SUBSCRIBER_INDEX;
static {
SUBSCRIBER_INDEX = new HashMap<Class<?>, SubscriberInfo>();
// 将方法信息存入 map 表中
putIndex(new SimpleSubscriberInfo(com.zzr.business.invest.InvestFragment.class, true,
new SubscriberMethodInfo[] {
new SubscriberMethodInfo("onRefreshData", com.zzr.model.OnRefreshInvestEvent.class, ThreadMode.MAIN),
}));
}
private static void putIndex(SubscriberInfo info) {
SUBSCRIBER_INDEX.put(info.getSubscriberClass(), info);
}
@Override
public SubscriberInfo getSubscriberInfo(Class<?> subscriberClass) {
SubscriberInfo info = SUBSCRIBER_INDEX.get(subscriberClass);
if (info != null) {
return info;
} else {
return null;
}
}
}
复制代码
apt 生成的这个文件将所有调用方法信息自动生成,以订阅者的 class 类型名为 key 存到 map 表中缓存。这样的效率显然要比反射查找要高很多。
private SubscriberInfo getSubscriberInfo(FindState findState) {
if (findState.subscriberInfo != null && findState.subscriberInfo.getSuperSubscriberInfo() != null) {
SubscriberInfo superclassInfo = findState.subscriberInfo.getSuperSubscriberInfo();
if (findState.clazz == superclassInfo.getSubscriberClass()) {
return superclassInfo;
}
}
if (subscriberInfoIndexes != null) {
// 从 subscriberInfoIndexes 中查找
for (SubscriberInfoIndex index : subscriberInfoIndexes) {
SubscriberInfo info = index.getSubscriberInfo(findState.clazz);
if (info != null) {
return info;
}
}
}
return null;
}
复制代码
总结
一遍分析下来,我们发现 EventBus 3.0 在性能上比之前提高了很多,前提是你开启了 Subscriber Index,唯一一处性能损耗就是调用订阅方法时是用反射调用的,不过这点影响几乎可以忽略不计。同时我们发现 APT 技术真的是非常强大,非常受各大框架的青睐。
虽然 EventBus 能帮助我们解耦代码,但是我们也不能滥用。滥用的话管理 Event 事件很不方便。所以只在关键地方用它,一些简单的地方使用回调、Activity 的 onActivityResult() 其实就可以了。
参考
https://github.com/greenrobot/EventBus
http://greenrobot.org/files/eventbus/javadoc/3.0/
http://greenrobot.org/eventbus/
https://kymjs.com/code/2015/12/12/01/
http://liuwangshu.cn/application/eventbus/2-eventbus-sourcecode.html