我有一些关于扩展Observable.OnSubscribe的排球请求的监听器,我希望在达到这些方法时使用rxjava发出消息。基本上我有:
public class CallListener implements Observable.OnSubscribe<Boolean>{
Boolean success;
public void onSucess() {
success = true;
// need to call call()
}
public void onError() {
success = false;
// need to call call()
}
@Override
public void call(Subscriber<? super Boolean> subscriber) {
// How can i call this method from onSuccess and onError ?
subscriber.onNext(success);
subscriber.onCompleted();
}
}
如何从onSuccess和onError调用call()方法?我的目标是使用观察者链接callListeners,它基本上是每个请求的UI控制器(创建加载,提供错误处理,保存json),而不必创建第三个类只是为了使callListener成为一个observable(我想发出消息)直接来自CallListener)。提前谢谢。
答案 0 :(得分:1)
我并不完全了解您的用例。但是,如果您只是尝试从成功/失败方法调用onNext和onComplete方法,您可以保留订阅引用并根据需要使用它。
public class CallListener implements Observable.OnSubscribe<Boolean>{
Boolean success;
Subscriber<? super Boolean> subscriber;
public void onSuccess() {
success = true;
// need to call callOnNext()
callOnNext();
}
public void onError() {
success = false;
// need to call callOnNext()
callOnNext();
}
@Override
public void call(Subscriber<? super Boolean> subscriber) {
this.subscriber = subscriber;
}
private void callOnNext(){
if(subscriber != null && !subscriber.isUnsubscribed()){
subscriber.onNext(success);
subscriber.onCompleted();
subscriber = null;
}
}
}