RxJava2总结之Subjects、Single与Completable

目录

Subjects

Subject可以看成是一个桥梁或者代理,在某些ReactiveX实现中(如RxJava),它同时充当 了Observer和Observable的角色。因为它是一个Observer,它可以订阅一个或多个 Observable;又因为它是一个Observable,它可以转发它收到(Observe)的数据,也可以发射 新的数据。

对我来说为什么用subjects呢?所有Subject都可以直接发射,不需要 发射器的引用 和 Observable.create()不同

  • AsyncSubject:简单的说使用AsyncSubject无论输入多少参数,永远只输出最后一个参数。
    但是如果因为发生了错误而终止,AsyncSubject将不会发射任何数据,只是简单的向前传递这个错误通知。
AsyncSubject<Integer> source = AsyncSubject.create();
    source.subscribe(o -> System.out.println("1:"+o)); // it will emit only 4 and onComplete
    source.onNext(1);
    source.onNext(2);
    source.onNext(3);
     <!-- it will emit 4 and onComplete for second observer also. -->
    source.subscribe(o -> System.out.println("2:"+o));
    source.onNext(4);
    source.onComplete();
    日志:
    1:4
    2:4
  • BehaviorSubject:会发送离订阅最近的上一个值,没有上一个值的时候会发送默认值。

如果原始的Observable因为发生了一个错误而终止,BehaviorSubject将不会发射任何 数据,只是简单的向前传递这个错误通知。

BehaviorSubject<Integer> source = BehaviorSubject.create();
        //默认值版本
//        BehaviorSubject<Integer> source = BehaviorSubject.createDefault(-1);
        source.subscribe(o -> System.out.println("1:"+o)); // it will get 1, 2, 3, 4 and onComplete
        source.onNext(1);
        source.onNext(2);
        source.onNext(3);
        <!-- it will emit 3(last emitted), 4 and onComplete for second observer also. -->
        source.subscribe(o -> System.out.println("2:"+o));
        source.onNext(4);
        source.onComplete();
        日志:
        1:1
        1:2
        1:3
        2:3
        1:4
        2:4
  • publishSubject(subject里最常用的):可以说是最正常的Subject,从那里订阅就从那里开始发送数据。

如果原始的Observable因为发生了一个错误而终止,PublishSubject将不会发射任何数据,只 是简单的向前传递这个错误通知。

PublishSubject bs = PublishSubject.create();
        bs.subscribe(o -> System.out.println("1:"+o));
        bs.onNext(1);
        bs.onNext(2);
        bs.subscribe(o -> System.out.println("2:"+o));
        bs.onNext(3);
        bs.onComplete();
        bs.subscribe(o -> System.out.println("3:"+o));
        日志:
        1:1
        1:2
        1:3
        2:3
  • replaySubject: 无论何时订阅,都会将所有历史订阅内容全部发出。
 ReplaySubject bs = ReplaySubject.create();
        bs.subscribe(o -> System.out.println("1:"+o));
// 无论何时订阅都会收到123
        bs.onNext(1);
        bs.onNext(2);
        bs.onNext(3);
        bs.onComplete();
        bs.subscribe(o -> System.out.println("2:"+o));
        日志:
        1:1
        1:2
        1:3
        2:1
        2:2
        2:3

Single与Completable

参考: 这里写链接内容

使用场景:其实这个网络请求并不是一个连续事件流,你只会发起一次 Get 请求返回数据并且只收到一个事件。我们都知道这种情况下 onComplete 会紧跟着 onNext 被调用,那为什么不把它们合二为一呢?

  • Single:它总是只发射一个值,或者一个错误通知,而不是发射 一系列的值。因此,不同于Observable需要三个方法onNext, onError, onCompleted,订阅Single只需要两 个方法:

Single只会调用这两个方法中的一个,而且只会调用一次,调用了任何一个方法之后,订阅关 系终止。

  • onSuccess - Single发射单个的值到这个方法
  • onError - 如果无法发射需要的值,Single发射一个Throwable对象到这个方法
<!--  retrofit 范例-->
 public interface APIClient {
     @GET("my/api/path")
     Single<MyData> getMyData();
 }
 apiClient.getMyData()
     .subscribe(new Consumer<MyData>() {
         @Override
         public void accept(MyData myData) throws Exception {
             // handle data fetched successfully and API call completed
         }
     }, new Consumer<Throwable>() {
         @Override
         public void accept(Throwable throwable) throws Exception{
             // handle error event
         }
     });
     <!-- 单独使用范例: -->
        Single.just("Amit")
            .subscribe(s -> System.out.println(s)
                    , throwable -> System.out.println("异常"));

使用场景:通过 PUT 请求更新数据 我只关心 onComplete 事件。使用 Completable 时我们忽略 onNext 事件,只处理 onComplete 和 onError 事件

  • Completable:本质上来说和 Observable 与 Single 不一样,因为它不发射数据。
<!--  retrofit 范例-->
public interface APIClient {
    @PUT("my/api/updatepath")
    Completable updateMyData(@Body MyData data);
}
apiClient.updateMyData(myUpdatedData)
    .subscribe(new Action() {
        @Override
        public void run() throws Exception {
            // handle completion
        }
    }, new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception{
            // handle error
        }
    });
    <!-- 单独使用范例: -->
     Completable.timer(1000, TimeUnit.MILLISECONDS)
                    .subscribe(() -> System.out.println("成功")
                            , throwable -> System.out.println("异常"));
  • andThen( Completable中的方法最常用):在这个操作符中你可以传任何Observable、Single、Flowable、Maybe或者其他Completable,它们会在原来的 Completable 结束后执行
apiClient.updateMyData(myUpdatedData)
    .andThen(performOtherOperation()) // a Single<OtherResult>
    .subscribe(new Consumer<OtherResult>() {
        @Override
        public void accept(OtherResult result) throws Exception {
            // handle otherResult
        }
    }, new Consumer<Throwable>() {
        @Override
        public void accept(Throwable throwable) throws Exception{
            // handle error
        }
    });
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值