Subscriber OnComplete called twice

2019-08-10 05:37发布

Why is the #onComplete() called twice even though the #addSomething() is called only once? This the code snippet:

private void addSomething() {
            Subscriber<AddCommentResponse> subscriber = createSubscriber();

            NetworkService.getIp()
                    .subscribeOn(Schedulers.io())
                    .flatMap(addSomethingService)
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(subscriber);
        }

        private Subscriber<AddCommentResponse> createSubscriber() {
            return new Subscriber<AddCommentResponse>() {
                @Override
                public void onCompleted() {
                    this.unsubscribe();

                    Toast.makeText(
                            MyApplication.context, getString(R.string.toast_comment_added_successfully), Toast.LENGTH_LONG
                    ).show();
                    navigateBack();
                }    

                @Override
                public void onNext(AddCommentResponse response) {
                    onCompleted();                        
                }
            };

1条回答
The star\"
2楼-- · 2019-08-10 05:58

RxJava follow this contract : it will call on your observer onNext then will end your stream with onComplete OR onError call.

You don't have to do it. RX will do it for you.

  • remove the onComplete() call from the onNext method : it's useless and it will fix your issue.
  • createSubscribe should return an Observer instead. A Subscriber is a Observer with a different meaning. (Subscribe method argument is Observer)
查看更多
登录 后发表回答