EventBus 引用

1、功能简述

全局事件(数据)传递,可减少一步一步传递数据的繁琐步骤。

2、gradle接入

(1)module的gradle添加加速索引,不同模块不能包名相同,不然会冲突。

android {
defaultConfig {
javaCompileOptions {
annotationProcessorOptions {
//EventBus 加速索引
arguments.put('eventBusIndex', 'org.eventbus.MyEventBusIndex')
}
}
}
}

(2)module的gradle接入插件

implementation('org.greenrobot:eventbus:3.0.0')
annotationProcessor('org.greenrobot:eventbus-annotation-processor:3.0.1')

(3)project的gradle中

dependencies {
  classpath "com.neenbedankt.gradle.plugins:android-apt:1.8"
  // ButterKnife R2支持
  
classpath 'com.jakewharton:butterknife-gradle-plugin:9.0.0-SNAPSHOT'

}
allprojects {
  repositories {
    google()
    mavenCentral()
    jcenter()
    maven { url "https://oss.sonatype.org/content/repositories/snapshots" }
  }
}

3、初始化

 EventBus.builder().addIndex(new MyEventBusIndex()).installDefaultEventBus();

4、使用方法

 (1)接受配置

@Subscribe(sticky = true)
public void onEventBusReceived(@NonNull EventBusDataBean data){
  // options
}
发送事件(数据):
EventBus.getDefault().postSticky(obj); //可用于加速索引
EventBus.getDefault().post(obj); //常规

备注:sticky = true 如果已有对应的数据,在注册时,会马上收到EventBus数据

(2)注册于解除注册

使用时,需要注册才能接收到数据:

EventBus.getDefault().register(this);

不使用时,解除注册:

EventBus.getDefault().unregister(this);

判断是否注册:

EventBus.getDefault().isRegistered(this);

posted @ 2019-01-05 09:53  后天打老虎  阅读(819)  评论(0编辑  收藏  举报