EventBus详解

2018-09-19  本文已影响0人  kjy_112233

一、EventBus使用

(1)EventBus作用

(2)EventBus三要素

(3)EventBus线程模型

(4)EventBus的基本用法

compile 'org.greenrobot:eventbus:3.1.1'
@Override 
protected void onCreate(Bundle savedInstanceState) { 
  super.onCreate(savedInstanceState); 
  setContentView(R.layout.activity_main);
  //注册事件
  EventBus.getDefault().register(this);
}
@Override
protected void onDestroy() {
    super.onDestroy();
    if(EventBus.getDefault().isRegistered(this)) {
        //解除注册
        EventBus.getDefault().unregister(this);
    }
}
EventBus.getDefault().post(message);
@Subscribe(threadMode = ThreadMode.MAIN)
public void setMessage(String message) {
    //接收message
}
EventBus.getDefault().postSticky(message);
removeStickyEvent();
removeAllStickyEvents();
@Subscribe(threadMode = ThreadMode.MAIN,sticky = true)
public void setMessage(String message) {
    //接收message
}
-keepattributes *Annotation*
-keepclassmembers class * {
    @org.greenrobot.eventbus.Subscribe <methods>;
}
-keep enum org.greenrobot.eventbus.ThreadMode { *; }
 
# And if you use AsyncExecutor:
-keepclassmembers class * extends org.greenrobot.eventbus.util.ThrowableFailureEvent {
    <init>(java.lang.Throwable);

(5)订阅者索引SubscriberIndex使用

android {
    defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments = [eventBusIndex: 'com.ee.cp.MyEventBusIndex']
            }
        }
    }
}

dependencies {
    compile 'org.greenrobot:eventbus:3.1.1'
    annotationProcessor 'org.greenrobot:eventbus-annotation-processor:3.1.1'
}
EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();

EventBus源码解析

上一篇下一篇

猜你喜欢

热点阅读