订阅者索引
原文地址:http://greenrobot.org/eventbus/documentation/subscriber-index/
订阅者索引是EventBus 3的新功能,它是一种可选择的优化,用来加快初始订阅者的注册。
可以使用EventBus注解处理器在编译期内创建订阅者索引文件,虽然不强制使用索引,但是在Android上推荐使用以便获得最好的性能。
索引前提
请注意:只有用@Subscribe注解的方法才能被编入索引,同时,Subscriber类和事件类必须是public。此外,由于Java注解本身的技术限制,@Subscribe注解在匿名类中无法识别。
当EventBus不能使用索引,它将会在运行时自动恢复到反射的方式。因此它仍然能继续工作,只是变慢了一些。
如何生成索引
使用annotationProcessor
如果你不是使用Android Gradle Plugin version 2.2.0 或更高版本,请使用android-apt的方式配置
要启用索引生成,你需要使用annotationProcessor属性将EventBus注解处理器添加到你的build中,同时设置eventBusIndex参数用来指定你想要生成的索引全路径类名。例如,将下面的部分添加到你的Gradle构建脚本中:
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [ eventBusIndex : 'com.example.myapp.MyEventBusIndex' ]
}
}
}
}
dependencies {
implementation 'org.greenrobot:eventbus:3.1.1'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}
使用kapt
如果你想在Kotlin中使用EventBus,你需要使用kapt代替annotationProcessor :
apply plugin: 'kotlin-kapt' // ensure kapt plugin is applied
dependencies {
implementation 'org.greenrobot:eventbus:3.1.1'
kapt 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}
kapt {
arguments {
arg('eventBusIndex', 'com.example.myapp.MyEventBusIndex')
}
}
使用android-apt
如果以上对你不起作用,你可以通过使用android-apt Gradle插件将EventBus注解处理器添加到你的构建中,将以下部分添加到你的Gradle构建脚本中:
buildscript {
dependencies {
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
}
}
apply plugin: 'com.neenbedankt.android-apt'
dependencies {
compile 'org.greenrobot:eventbus:3.1.1'
apt 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}
apt {
arguments {
eventBusIndex "com.example.myapp.MyEventBusIndex"
}
}
如何使用索引
成功构建了项目之后,将会为你生成eventBusIndex指定的类,然后在设置EventBus的时候像下面这样传递过去:
EventBus eventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();
或者,你想在你想在整个APP中使用默认的实例:
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
// Now the default instance uses the given index. Use it like this:
EventBus eventBus = EventBus.getDefault();
建立库索引
你可以用相同的原理应用到你的库中(不是最终应用),这样,你可以拥有多个index类,你可以在设置EventBus时添加这些索引类,例如:
EventBus eventBus = EventBus.builder()
.addIndex(new MyEventBusAppIndex())
.addIndex(new MyEventBusLibIndex()).build();