我有一个像这样的Observable:
@GET("endpoint")
Observable<Something> getSomething();
和订阅者一样
Subscriber<Something> somethingSubscriber = new Subscriber<Something>() {
public void onCompleted() {
}
public void onError(Throwable e) {
//handle exceptions
}
public void onNext() {
//do something
}
在与按钮关联的OnClickListener中,我进行了订阅
getSomething()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(somethingSubscriber);
如果我没有互联网连接,则会调用onError并执行一些异常处理。当我再次按下按钮(假设我想重试)时,不会调用回调方法。
我希望每次按下按钮都会调用onNext / onError回调。
答案 0 :(得分:2)
RxJava有extention。它有很多&#34;酷工具&#34;,但是为了处理改造错误,你可以使用ResponseOrError
类。
所以在你的情况下,它看起来像:
final PublishSubject<Object> clickSubject = PublishSubject.create();
final Observable<ResponseOrError<Something>> responseOrErrorObservable = clickSubject
.flatMap(new Func1<Object, Observable<ResponseOrError<Something>>>() {
@Override
public Observable<ResponseOrError<Something>> call(Object o) {
return getSomething()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.compose(ResponseOrError.<Something>toResponseOrErrorObservable());
}
})
.replay(1)
.refCount();
final Observable<Throwable> error = responseOrErrorObservable
.compose(ResponseOrError.<Something>onlyError())
.subscribe(new Action1<Segment>() {
@Override
public void call(Throwable throwable) {
// what to do on error, some toast or what ever yu need
}
});
final Observable<UserInfoResponse> success = responseOrErrorObservable
.compose(ResponseOrError.<Something>onlySuccess())
.subscribe(new Action1<Something>() {
@Override
public void call(Something some) {
// code what to do on success
}
});
现在,在onClick中你只需要放clickSubject.onNext(null)
.replay(1).refCount();
,因为有2个Observable使用responseOrErrorObservable
,所以没有它,改装请求将会发生&#34;发生&#34;两次。
答案 1 :(得分:1)
使用此代码
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
getSomething()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<Something>() {
@Override
public void call(Something something) {
//do something
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
//handle exceptions
}
},
new Action0() {
@Override
public void call() {
}
});
}
});
<强>加成强>
或
替换此
Subscriber<Something> somethingSubscriber = new Subscriber<Something>() {
public void onCompleted() {
}
public void onError(Throwable e) {
//handle exceptions
}
public void onNext() {
//do something
}
};
到
Subscriber<String> somethingSubscriber = new Subscriber<String>() {
@Override
public void onCompleted() {
}
@Override
public void onError(Throwable e) {
}
@Override
public void onNext(String s) {
}
};
答案 2 :(得分:1)
您正在重复使用相同的订阅者。一旦你得到onError或结果(所以它完成),订阅者就会被取消订阅。尝试每次都有新用户通过。
答案 3 :(得分:0)
在我的案例中,由于模型类的解析错误而未调用onNext()和onError()方法,我将一个双精度对象作为Integer进行了操作,因此引发了NumberFormatException异常,并且在从改造中获取结果后没有任何反应。