我想了解我何时使用

    Observable.just(1).subscribe(new Observer<Integer>() {

        Disposable disposable;

        @Override
        public void onSubscribe(Disposable disposable) {
            System.out.println("Subscribed");
            this.disposable = disposable;
        }

        @Override
        public void onNext(Integer integer) {
            System.out.println(integer);
            System.out.println(disposable.isDisposed());
        }

        @Override
        public void onError(Throwable throwable) {
            System.out.println("Error");
            System.out.println(disposable.isDisposed());
        }

        @Override
        public void onComplete() {
            System.out.println("Complete");
            System.out.println(disposable.isDisposed());
        }
    })


OnCompleteOnError之后,disposable.isDisposed()返回true,与我使用时一样

  Observable.create(new ObservableOnSubscribe<Integer>() {
        @Override
        public void subscribe(ObservableEmitter<Integer> observableEmitter) throws Exception {
            if (!observableEmitter.isDisposed())
                observableEmitter.onComplete();
        }
    }).subscribe(new Observer<Integer>() {

        Disposable disposable;

        @Override
        public void onSubscribe(Disposable disposable) {
            System.out.println("Subscribed");
            this.disposable = disposable;
        }

        @Override
        public void onNext(Integer integer) {
            System.out.println(integer);
            System.out.println(disposable.isDisposed());
        }

        @Override
        public void onError(Throwable throwable) {
            System.out.println("Error");
            System.out.println(disposable.isDisposed());
        }

        @Override
        public void onComplete() {
            System.out.println("Complete");
            System.out.println(disposable.isDisposed());
        }
    });


我看到disposable.isDisposed()返回false。有人可以解释我的真实情况吗?我了解写得很好的Observable.create不得在onComplete()onError()之后发出项目。

最佳答案

Disposable仅持有对subscription的引用,要对其进行处置,您需要调用disposable.dispose()Observable不会在complete方法上处置Disposable实例。

 @Override
        public void onComplete() {
            System.out.println("Complete");
            disposable.dispose();
            System.out.println(disposable.isDisposed());
        }

07-24 09:21