前言
EvenBus 2.x时代的消息订阅只能使用固定的方法名,比如:
onEvent
onEventMainThread
onEventBackgroundThread
onEventAsync
从EventBus 3.0开始支持使用注解来定义消息订阅者(subscriber),方法名是随意的,比如:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
// Do something
}
不过,EventBus3.0还有一个鲜为人知的功能,而且是一个可选的功能,默认是不带的,需要手动添加支持。
那就是使用APT在编译期间搜集所有的SubscribMethod。默认是在运行期间通过反射去搜集SubscriberMethod,这样性能就差点。
EventBus添加APT支持
在EventBus的github主页上有一个不起眼的地方,有提到建议使用APT(只是建议不是必须使用):

点击这个链接会跳转到单独介绍如何使用subscriber index(APT生成的代码)的指南页面:
https://greenrobot.org/eventbus/documentation/subscriber-index/
下面通过实践介绍如何使用subscriber index来提升EventBus的性能。
关于EventBus集成subscriber index很简单,先通过kapt额外添加eventbus-annotation-processor依赖:
dependencies {
implementation "org.greenrobot:eventbus:3.2.0"
kapt "org.greenrobot:eventbus-annotation-processor:3.2.0"
}
然后给APT添加参数,注明生成subscriber index类的路径:
defaultConfig {
kapt {
arguments {
arg('eventBusIndex', 'com.devnn.bean.AppEventBusIndex')
}
}
}
这个类是自动生成的,不需要手动去创建,命名可以随意。
build项目之后就会在build目录生成Java类:com.devnn.bean.AppEventBusIndex.java
然后需要在app启动时将这个类注册进EventBus中:
class MyApp :Application(){
override fun onCreate() {
super.onCreate()
EventBus.builder().addIndex(AppEventBusIndex()).build()
}
}
其它像以前一样正常使用EventBus即可。
关于APT有不了解的可以看笔者另一篇文章:
Google AutoService的使用与源码解析
下面分析这个类的作用。
EventBus APT流程分析
EventBus是通过建造者模式构建的,在EventBusBuilder类通过addIndex方法接收SubscriberInfoIndex对象:
/** Adds an index generated by EventBus' annotation preprocessor. */
public EventBusBuilder addIndex(SubscriberInfoIndex index) {
if (subscriberInfoIndexes == null) {
subscriberInfoIndexes = new ArrayList<>();
}
subscriberInfoIndexes.add(index);
return this;
}
而SubscriberInfoIndex是一个接口:
package org.greenrobot.eventbus.meta;
/**
* Interface for generated indexes.
*/
public interface SubscriberInfoIndex {

本文介绍如何使用APT生成SubscriberIndex以提高EventBus3.0的性能,包括集成步骤及原理分析。
最低0.47元/天 解锁文章
1万+

被折叠的 条评论
为什么被折叠?



