EventBus是我们在跨线程中,使用较多的一个开源通信组件了。那么你真的知道怎么使用EventBus吗?
如果使用过EventBus几年,并了解过EventBus源码的同学就会知道,EventBus在register注册时,起初只是使用反射来查找以onEvnet开头的方法来处理消息,也就是onEventxXXX就是我们订阅类的消息处理方法。
我们都知道反射是有一定的性能损耗的。所以,后来EventBus加入了注解@Subscribe,来提高代码效率,同时也不用在限制我们的方法名了,哈哈...
常规写法
那么,我们是不是这么使用的?
1. 定义一个事件:
public static class MessageEvent { /* Additional fields if needed */ }
2. 订阅消息事件:
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
接收对应的消息:
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {/* Do something */};
3. 发送消息
EventBus.getDefault().post(new MessageEvent());
4. gradle接入
project的build.gradle配置:
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
app或lib的build.gradle配置:
导入插件:
apply plugin: 'org.greenrobot.greendao'
导入依赖:
implementation 'org.greenrobot:eventbus:3.1.1'
然后就可以了?
真的是这样吗?确定有看过EventBus的源码吗?
没事,现在你可以看看这篇,了解下EventBus注解是怎么实现的。
并不是说上面的写法有错误,而是上面的写法没有利用起来@Subscribe作为注解的作用,所以上面的写法在注册的时候使用的是反射来查找对应的注解方法,而不是从MyEventBusIndex类中查找已经存储好的注解方法,也就是效率没有注解那么高。
下面说下EventBus的高效配置方式:
kotlin项目配置:
1. project项目的build.gradle配置
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
2. app的build.gralde配置
apply plugin: 'org.greenrobot.greendao'
apply plugin: 'kotlin-kapt'
依赖配置:
dependencies {
// ...
implementation 'org.greenrobot:eventbus:3.1.1'
kapt 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}
路径配置:
android {
// ...
kapt {
arguments {
arg('eventBusIndex', 'com.victor.eventbusdemo.MyEventBusIndex')
}
}
}
然后rebuild一下便会产生我们的MyEventBusIndex类。
还没完呢!
最后将我们的MyEventBusIndex类配置到EventBus中:
EventBus.builder().addIndex(MyEventBusIndex()).installDefaultEventBus()
java项目配置:
项目的build.gralde:
classpath 'org.greenrobot:greendao-gradle-plugin:3.2.2'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.8'
modle的build.gradle :
路径配置:
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [ eventBusIndex : 'com.victor.eventbusdemo.MyEventBusIndex' ]
}
}
}
依赖配置:
implementation 'org.greenrobot:eventbus:3.1.1'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
最后别忘了设置我们的MyEventBusIndex到EventBus中:
EventBus.builder().addIndex(MyEventBusIndex()).installDefaultEventBus()
大功告成。