RXJAVA之Subject

  RxJava中常见的Subject有4种,分别是 AsyncSubject、 BehaviorSubject、PublishSubject、 ReplaySubject。

AsyncSubject

  使用AsyncSubject无论输入多少参数,永远只输出最后一个参数。

BehaviorSubject

  BehaviorSubject会发送离订阅最近的上一个值,没有上一个值的时候会发送默认值。

BehaviorSubject<Integer> subject = BehaviorSubject.create();
        subject.onNext(1);
        subject.onNext(2);
        subject.onNext(3);
        subject.onNext(4);
        subject.subscribe(new Consumer<Integer>(){
            @Override
            public void accept(Integer t) throws Exception {
                System.out.println(t);
                
            }});

PublishSubject

  使用PublishSubject从那里订阅就从那里开始发送数据。

PublishSubject<Integer> subject = PublishSubject.create();
        subject.onNext(1);
        subject.subscribe(new Consumer<Integer>(){
            @Override
            public void accept(Integer t) throws Exception {
                System.out.println(t);
                
            }});
        subject.onNext(2);
        subject.onNext(3);
        subject.onNext(4);

  输出结果2 3 4.

ReplaySubject

  无论何时订阅,都会将所有历史订阅内容全部发出。

ReplaySubject<Integer> subject = ReplaySubject.create();
        subject.onNext(1);
        subject.subscribe(new Consumer<Integer>(){
            @Override
            public void accept(Integer t) throws Exception {
                System.out.println(t);
                
            }});
        subject.onNext(2);
        subject.onNext(3);
        subject.onNext(4);

  输出结果1 2 3 4.

 

posted @ 2017-11-28 16:35  zwh1988  阅读(373)  评论(0编辑  收藏  举报