在doOnSubscribe中调用subject.onNext()

时间:2017-04-06 11:09:08

标签: java rx-java2

为什么在subject.onNext(o)内调用doOnSubscribe无效,但调用subject.onComplete()会导致流终止!

final PublishSubject<Integer> subject = PublishSubject.create();

    final Observable<Integer> observable = subject.doOnSubscribe(new Consumer<Disposable>() {
        @Override
        public void accept(@NonNull Disposable disposable) throws Exception {
            System.out.println("disposable = [" + disposable + "]");
            subject.onNext(1);
            //or
            Observable.just(2, 3).subscribe(subject);
        }
    });

    observable.subscribe(new Observer<Integer>() {
        @Override
        public void onSubscribe(Disposable d) {
            System.out.println("d = [" + d.isDisposed() + "]");
        }

        @Override
        public void onNext(Integer integer) {
            System.out.println("item = [" + integer + "]");
        }

        @Override
        public void onError(Throwable e) {
            System.out.println("e = [" + e + "]");
        }

        @Override
        public void onComplete() {
            System.out.println("onComplete");
        }
    });/*
    expected:
    disposable = [false]
    d = [false]
    item = 1
    item = 2
    item = 3
    onComplete
    but received :
    disposable = [false]
    d = [false]
    onComplete
    */

1 个答案:

答案 0 :(得分:2)

订阅2.x中的Subject时,代表该连接的Disposable正在遍历onSubscribe()链,然后Observer变为onNext可见}}。如果您从hasObservers致电onSubscribe,您会看到这一点,它会返回false,直到onSubscribe实际返回。

这是Observable协议所要求的,因为不允许同时运行onSubscribeonNext,而onSubscribe必须在onNext之前运行。如果此规则未被保留,则Subject.onNext的并发呼叫将在Observer.onSubscribe呼叫之前或甚至同时运行,并找到可能没有准备的消费者。

由于PublishSubject未保留任何onNext次调用,因此会删除未观察到的onNext项。根据使用情况,您应该使用BehaviorSubjectyourSubject.startWith(initialValue).subscribe()来获取onNext中任何其他Subject之前的值。