经常我们会有这样的需求,B页面操作后,要求A页面处理相关数据,像这样一般我们都是,要么B页面保留A页面的引用,要么使用广播,但是写起来还是想对麻烦的,用Rxbus就可以很容易和优雅的解决
Otto(不再维护不推荐使用)和EventBus
Rxjava的话 我就比较推荐用Rxbus了
Rxjava 那还是使用EventBus 吧 毕竟Rxbus只有500+的Star 而EventBus可是1W+ 而且Rxbus`很多地方还不完善
总的来说 我们要做的无外乎两件事:发送事件 和 接受事件
但是接受事件的对象一定要先注册到Rxbus中
添加引用
implementation 'com.hwangjr.rxbus:rxbus:2.0.0'@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RxBus.get().register(this);
}
@Override
protected void onDestroy() {
RxBus.get().unregister(this);
super.onDestroy();
}发送事件有两种方式一种为
@Produce(
thread = EventThread.IO,
tags = {
@Tag("007")
}
)
public ArrayList<String> produce02() {
ArrayList<String> words = new ArrayList<>();
words.add("好好学习");
words.add("天天向上");
return words;
}可以看出我们加了Produce注解
加了这个注解就会在注册的时候发送事件
接收方 会根据 设置的Tag和返回的数据类型来调用相应的方法,于方法名无关
当然也可以不写tags和thread
tags为rxbus_default_tagthread为EventThread.MAIN_THREAD例如
@Produce
public String produce01() {
return "页面初始化加载!";
}RxBus.get().post("我是新数据");
RxBus.get().post("007","我是新数据(自定义Tag)");Subscribe注解
方法名无关 只和tags和传入的参数类型有关
interface类型 也就是说数据类型不能像List<String>这样,必须为ArrayList<String>这样的
tags一样`类型也一样`的多个方法,都会接受到相应的事件
默认tags和thread
@Subscribe
public void subscribe02(String word) {
Snackbar.make(getWindow().getDecorView(), word, Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}自定义tags和thread
@Subscribe(
thread = EventThread.MAIN_THREAD,
tags = {
@Tag("007")
}
)
public void subscribe03(ArrayList<String> words) {
Snackbar.make(getWindow().getDecorView(), words.toString(), Snackbar.LENGTH_SHORT)
.setAction("Action", null).show();
}