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()
大功告成。