Java高阶编程——RxBus 开源,基于 RxJava 的 event bus

介绍

RxBus 是一个发布/订阅模式的事件总线,用法和 EventBus 一样简单。RxBus 基于 RxJava 开发,除了拥有和 EventBus

一样简单的事件总线机制之外,还拥有 RxJava 的丰富特性。

Java高阶编程——RxBus 开源,基于 RxJava 的 event bus

如何使用

  1. 定义 EventData:
  2. public static class EventData { /* Additional fields if needed */ }
  3. 注解定义订阅者的回调方法,回调方法回在 UI 线程中执行:
  4. @RegisterBus
  5. public void onMessageEvent(MessageEvent event) {/* Do something */};
  6. 注册/解注册。 观察者需要被注册到 RxBus,其 @RegisterBus 标记的方法才会被扫描到,在不需要的地方记得解注册。
  7. @Override
  8. protected void onCreate(Bundle savedInstanceState) {
  9. super.onCreate(savedInstanceState);
  10. setContentView(R.layout.activity_main);
  11. initView();
  12. // register to RxBus
  13. RxBus.getInstance().register(this);
  14. }
  15. @Override
  16. protected void onDestroy() {
  17. super.onDestroy();
  18. // unregister from RxBus
  19. RxBus.getInstance().unRegister(this);
  20. }
  21. 发送数据:

// send data in thread

Data data = new Data();

Data.setContent("hello world");

RxBus.getInstance().send(data);

比 EventBus 多的优点

RxBus 提供 chainProcess 方法来包装一个处理过程, 处理结果会自动发送到观察者。

Java高阶编程——RxBus 开源,基于 RxJava 的 event bus

  1. 在 MVP 架构的 M 层你可以这样用
  2. RxBus.getInstance().chainProcess(new Func1() {
  3. @Override
  4. public Object call(Object o) {
  5. // do something in IO thread, the return data can be subscribe and receive.
  6. // getUser() is a IO/net process
  7. User user = getUser();
  8. user.setId(uid);
  9. user.setName("大利猫");
  10. return user;
  11. }
  12. });
  13. 然后在 P 层接收:
  14. /**
  15. * @RegisterBus mark this method to receive data in UI thread
  16. * @param user
  17. */
  18. @RegisterBus
  19. public void onUser(User user) {
  20. userView.showUser(user);
  21. }

Gradle independence

Step 1. Add the JitPack repository to your build file, Add it in your root build.gradle at the end of repositories:

allprojects {

repositories {

...

maven { url 'https://jitpack.io' }

}

}

Step 2. Add the dependency

dependencies {

compile 'com.github.liuguangli:RxBus:1.1'

}

欢迎加入Java高级架构学习交流群:468947140

进群获取架构资料 还有在大型企业工作十余年的架构师分享经验,Java工程化管理、高性能、分布式、高可用架构、zookeeper、Spring cloud,MyBatis,Netty源码分析和大数据等多个知识点高级进阶干货

进群修改群备注:开发年限-地区-经验

点击链接加入群聊【Java-BATJ企业级资深架构】:https://jq.qq.com/?_wv=1027&k=52j2FVO

源码地址

https://github.com/liuguangli/RxBus

猜你喜欢

转载自blog.csdn.net/SpringJavaMyBatis/article/details/82023216