EventBus3 使用方法
程序员文章站
2022-07-04 10:19:42
...
EventBus 3
EventBus 是一个基于观察者模式的事件发布/订阅框架
资料
设置
导入
- 配置模组的 build.gradle
android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
arguments = [ eventBusIndex : 'com.example.myapp.MyEventBusIndex' ] // 索引全名
}
}
}
}
dependencies {
compile 'org.greenrobot:eventbus:3.0.0'
annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.0.1'
}
初始化
// 设置为默认属性
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();
EventBus eventBus = EventBus.getDefault(); // 设置完后,使用默认即可
// 或者在使用时再设置
EventBus eventBus = EventBus.builder().addIndex(new MyEventBusIndex()).build();
// 如果库中有EventBusIndex,需要多次添加
EventBus eventBus = EventBus.builder()
.addIndex(new MyEventBusAppIndex())
.addIndex(new MyEventBusLibIndex())
.build();
混淆
-keepattributes *Annotation*
-keepclassmembers class ** {
@org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
# Only required if you use AsyncExecutor
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
<init>(java.lang.Throwable);
}
基本用法
定义事件Event
public class MessageEvent {
public final String message;
public MessageEvent(String message) {
this.message = message;
}
}
注册
订阅之前需要注册,activities和fragments一般在 onStart/onStop 中调用
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
订阅
四种线程模式,ThreadMode: POSTING
/MAIN
/BACKGROUND
/ASYNC
// 在发送事件的线程调用,同步处理
@Subscribe
public void handleSomethingElse(SomeOtherEvent event) {
doSomethingWith(event);
}
// 主线程调用
@Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MessageEvent event) {
Toast.makeText(getActivity(), event.message, Toast.LENGTH_SHORT).show();
}
// 子线程调用,非主线程则直接调用,主线程则开单线程调用
@Subscribe(threadMode = ThreadMode.BACKGROUND)
public void onMessage(MessageEvent event){
saveToDisk(event.message);
}
// 异步调用,使用线程池在不同的线程调用
@Subscribe(threadMode = ThreadMode.ASYNC)
public void onMessage(MessageEvent event){
backend.send(event.message);
}
发送
任意地方发送事件,匹配的事件订阅方法会接收事件
EventBus.getDefault().post(new MessageEvent("Hello everyone!"));
优先级
@Subscribe(priority = 1); // 优先级,默认为0
public void onEvent(MessageEvent event) {
// 取消传递,只能运行在ThreadMode.PostThread
EventBus.getDefault().cancelEventDelivery(event);
}
粘性事件 Sticky Event
事件发出后一直保存在内存中,订阅方法在之后注册也能完成订阅
用法
EventBus.getDefault().postSticky(new MessageEvent("Hello everyone!"));
@Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
@Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
public void onEvent(MessageEvent event) {
textField.setText(event.message);
}
@Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
取消事件
MessageEvent stickyEvent = EventBus.getDefault().getStickyEvent(MessageEvent.class);
if(stickyEvent != null) {
EventBus.getDefault().removeStickyEvent(stickyEvent);
}
MessageEvent stickyEvent = EventBus.getDefault().removeStickyEvent(MessageEvent.class);
if(stickyEvent != null) {
}
配置
无订阅时无日志
EventBus eventBus = EventBus.builder()
.logNoSubscriberMessages(false)
.sendNoSubscriberEvent(false)
.build();
抛异常
EventBus eventBus = EventBus.builder().throwSubscriberException(true).build();
修改默认
EventBus.builder().throwSubscriberException(BuildConfig.DEBUG).installDefaultEventBus();
异步执行器 AsyncExecutor
- AsyncExecutor就像一个带异常处理的线程池
- 异常被自动捕获包裹成ThrowableFailureEvent并发送
用法
AsyncExecutor.create() // 在 Application 中创建保存实例
.execute(new AsyncExecutor.RunnableEx() {
@Override
public void run() throws LoginException {
// 不需要捕获异常
remote.login();
EventBus.getDefault().postSticky(new LoggedInEvent());
}
}
);
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void handleLoginEvent(LoggedInEvent event) {
}
@Subscribe(threadMode = ThreadMode.MAIN)
public void handleFailureEvent(ThrowableFailureEvent event) {
// 处理异常
}
自定义
AsyncExecutor.builder()
- 可定义EventBus实例、线程池、失败事件类、作用域