EventBus索引加速探究,积累总结

本文探讨了EventBus如何通过注解处理器生成索引以提高性能。`EventBusBuilder.addIndex()`方法用于添加由注解处理器创建的索引,使得在不使用注解处理器的情况下,EventBus将依赖反射和遍历来查找订阅者。编译时,EventBusAnnotationProcessor会生成Java文件,其中包含了订阅者及其方法的映射。通过`EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();`将索引加入,以提升事件分发效率。分析了`EventBusAnnotationProcessor`的`process()`、`collectSubscribers()`和`createInfoIndexFile()`关键方法的工作流程。
摘要由CSDN通过智能技术生成

// EventBusBuidler.java

/** Adds an index generated by EventBus’ annotation preprocessor. */

public EventBusBuilder addIndex(SubscriberInfoIndex index) {

if (subscriberInfoIndexes == null) {

subscriberInfoIndexes = new ArrayList<>();

}

subscriberInfoIndexes.add(index);

return this;

}

通过 addIndex()SubscriberInfoIndex 往这个列表里面加。再往上找,没有了,addIndex()没有出现在任意一处被调用的地方。

也就是说,这个方法,是外部调用的。

它的英文注释我翻译一下:通过EventBus的注解处理器添加一个索引

这就说明了这个方法,是由注解器产生的Java文件调用。这也说明了,如果我们不使用注解处理器,EventBus寻找 @Subcriber的做法,永远是 反射 + 遍历。

2. 通过EventBusAnnotationProcessor生成Java文件

==========================================================================================================

EventBusAnnotationProcessor 需要引入,示例代码如下:

// build.gradle

android {

defaultConfig {

javaCompileOptions {

annotationProcessorOptions {

arguments = [ eventBusIndex : ‘com.example.myapp.MyEventBusIndex’ ]

}

}

}

}

dependencies {

def eventbus_version = ‘3.2.0’

implementation “org.greenrobot:eventbus:$eventbus_version”

annotationProcessor “org.greenrobot:eventbus-annotation-processor:$eventbus_version”

}

然后在项目中,写入 @Subscribe方法:

public class MainActivity extends AppCompatActivity {

@Subscribe(threadMode = ThreadMode.MAIN)

public void onMainActivityEvent(MainActivityEvent event){

}

}

点击编译,就会在下图目录中看到编译时生成的文件:

在这里插入图片描述

来看下文件内容:

public class MyEventBusIndex implements SubscriberInfoIndex {

private static final Map<Class<?>, SubscriberInfo

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值