本文介绍了订户OnComplete调用了两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
即使#addSomething()仅被调用一次,为什么#onComplete()也被调用两次?这是代码片段:
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();
}
};
推荐答案
RxJava遵循以下约定:它将调用您的观察者onNext,然后使用onComplete或onError调用结束流.
RxJava follow this contract : it will call on your observer onNext then will end your stream with onComplete OR onError call.
您不必这样做. RX将为您做到.
You don't have to do it. RX will do it for you.
- 从onNext方法中删除onComplete()调用:它没有用,它将解决您的问题.
- createSubscribe应该返回一个观察者.订户是具有不同含义的观察者. (Subscribe方法的参数是Observer)
这篇关于订户OnComplete调用了两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!