Rxbus的使用

Rxbus是一种模式,在RxJava中

一、添加依赖

1 compile 'io.reactivex:rxandroid:1.2.0'
2 compile 'io.reactivex:rxjava:1.1.5'

二、包装 --- 创建类

 1 public class RxBus {
 2     private static volatile RxBus sRxBus;
 3     // 主题
 4     private final Subject<Object, Object> mBus;
 5 
 6     // PublishSubject只会把在订阅发生的时间点之后来自原始Observable的数据发射给观察者
 7     public RxBus() {
 8         mBus = new SerializedSubject<>(PublishSubject.create());
 9     }
10 
11     // 单例RxBus
12     public static RxBus getInstance() {
13         if (sRxBus == null) {
14             synchronized (RxBus.class) {
15                 if (sRxBus == null) {
16                     sRxBus = new RxBus();
17                 }
18             }
19         }
20         return sRxBus;
21     }
22 
23     // 提供了一个新的事件
24     public void post(Object o) {
25         mBus.onNext(o);
26     }
27 
28     // 根据传递的 eventType 类型返回特定类型(eventType)的 被观察者
29     public <T> Observable<T> toObservable(Class<T> eventType) {
30         return mBus.ofType(eventType);
31 //        ofType = filter + cast
32 //        return mBus.filter(new Func1<Object, Boolean>() {
33 //            @Override
34 //            public Boolean call(Object o) {
35 //                return eventType.isInstance(o);
36 //            }
37 //        }) .cast(eventType);
38     }
39 }

说明:

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

三、创建发送的事件类

  发送 toObservable(Class<T> eventType)  事件.class

 1 public class ChannelItemMoveEvent {
 2     private int fromPosition;
 3     private int toPosition;
 4 
 5     public int getFromPosition() {
 6         return fromPosition;
 7     }
 8 
 9     public int getToPosition() {
10         return toPosition;
11     }
12 
13     public ChannelItemMoveEvent(int fromPosition, int toPosition) {
14         this.fromPosition = fromPosition;
15         this.toPosition = toPosition;
16 
17     }
18 }

四、发送事件

1 RxBus.getInstance().post(new ChannelItemMoveEvent(fromPosition, toPosition));

五、接收事件

1 mSubscription = RxBus.getInstance().toObservable(ChannelItemMoveEvent.class)
2                 .subscribe(new Action1<ChannelItemMoveEvent>() {
3                     @Override
4                     public void call(ChannelItemMoveEvent channelItemMoveEvent) {
5                         int fromPosition = channelItemMoveEvent.getFromPosition();
6                         int toPosition = channelItemMoveEvent.getToPosition();7                     }
8                 });

六、取消订阅

一般会在基类有一个成员变量 mSubscription,并在OnDestroy的时机取消订阅。

1  @Override
2     protected void onDestroy() {
3         if (mSubscription!= null && !mSubscription.isUnsubscribed()) {
4             mSubscription.unsubscribe();
5         }
6     }
原文地址:https://www.cnblogs.com/aimqqroad-13/p/7112460.html