Subscriber OnComplete called twice

妖精的绣舞 提交于 2019-12-11 10:09:45

问题


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:


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)


来源:https://stackoverflow.com/questions/29462592/subscriber-oncomplete-called-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!