RxBus的实现和使用

来源:互联网 发布:shake it off动作数据 编辑:程序博客网 时间:2024/05/18 03:39


RxBus并不是一个库,而是一种模式。相信大多数开发者都使用过EventBus,作为事件总线通信库,如果你的项目已经加入RxJava和EventBus,不妨用RxBus代替EventBus,以减少库的依赖。

一、添加RxJava和RxAndroid依赖

  1. //RxJava and RxAndroid
  2. compile 'io.reactivex:rxandroid:1.1.0'
  3. compile 'io.reactivex:rxjava:1.1.0'

二、新建RxBus类

不多说直接上代码:

  1. import rx.Observable;
  2. import rx.subjects.PublishSubject;
  3. import rx.subjects.SerializedSubject;
  4. import rx.subjects.Subject;
  5. /**
  6. * Created by ywh on 2017/2/8
  7. */
  8. public class RxBus {
  9. private static volatile RxBus mInstance;
  10. private final Subject bus;
  11. public RxBus()
  12. {
  13. bus = new SerializedSubject<>(PublishSubject.create());
  14. }
  15. /**
  16. * 单例模式RxBus
  17. *
  18. * @return
  19. */
  20. public static RxBus getInstance()
  21. {
  22. RxBus rxBus2 = mInstance;
  23. if (mInstance == null)
  24. {
  25. synchronized (RxBus.class)
  26. {
  27. rxBus2 = mInstance;
  28. if (mInstance == null)
  29. {
  30. rxBus2 = new RxBus();
  31. mInstance = rxBus2;
  32. }
  33. }
  34. }
  35. return rxBus2;
  36. }
  37. /**
  38. * 发送消息
  39. *
  40. * @param object
  41. */
  42. public void post(Object object)
  43. {
  44. bus.onNext(object);
  45. }
  46. /**
  47. * 接收消息
  48. *
  49. * @param eventType
  50. * @param <T>
  51. * @return
  52. */
  53. public <T> Observable<T> toObserverable(Class<T> eventType)
  54. {
  55. return bus.ofType(eventType);
  56. }
  57. }

1、Subject同时充当了Observer和Observable的角色,Subject是非线程安全的,要避免该问题,需要将 Subject转换为一个SerializedSubject,上述RxBus类中把线程非安全的PublishSubject包装成线程安全的Subject。
2、PublishSubject只会把在订阅发生的时间点之后来自原始Observable的数据发射给观察者。
3、ofType操作符只发射指定类型的数据,其内部就是filter+cast

三、创建你需要发送的事件类

我们这里用StudentEvent举例

  1. /**
  2. * Created by ywh on 2017/2/8
  3. */
  4. public class StudentEvent {
  5. private String id;
  6. private String name;
  7. public StudentEvent(String id, String name) {
  8. this.id = id;
  9. this.name = name;
  10. }
  11. public String getId() {
  12. return id;
  13. }
  14. public void setId(String id) {
  15. this.id = id;
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. }

四、发送事件

  1. RxBus.getInstance().post(new StudentEvent("007","小明"));

五、接收事件

  1. rxSbscription=RxBus.getInstance().toObserverable(StudentEvent.class)
  2. .subscribe(new Action1<StudentEvent>() {
  3. @Override
  4. public void call(StudentEvent studentEvent) {
  5. textView.setText("id:"+ studentEvent.getId()+" name:"+ studentEvent.getName());
  6. }
  7. });

注:rxSbscription是Sbscription的对象,我们这里把RxBus.getInstance().toObserverable(StudentEvent.class)赋值给rxSbscription以方便生命周期结束时取消订阅事件

六、取消订阅

  1. @Override
  2. protected void onDestroy() {
  3. if (!rxSbscription.isUnsubscribed()){
  4. rxSbscription.unsubscribe();
  5. }
  6. super.onDestroy();
  7. }


0 0
原创粉丝点击