.subscribe(
new Action1<Response>() {
@Override
public void call(Response response) {
if (response.isSuccess())
//handle success
else
//throw an Throwable(reponse.getMessage())
}
},
new Action1<Throwable>() {
@Override
public void call(Throwable throwable) {
//handle Throwable throw from onNext();
}
}
);
I don't wanna handle (!response.isSuccess())
in onNext()
. How can I throw it to onError()
and handle with other throwable together?
If FailureException extends RuntimeException
, then
.doOnNext(response -> {
if(!response.isSuccess())
throw new FailureException(response.getMessage());
})
.subscribe(
item -> { /* handle success */ },
error -> { /* handle failure */ }
);
This works best if you throw the exception as early as possible, as then you can do retries, alternative responses etc. easily.
you can flatMap
your response to Response or Error
flatMap(new Func1<Response, Observable<Response>>() {
@Override
public Observable<Response> call(Response response) {
if(response.isSuccess()){
return Observable.just(response);
} else {
return Observable.error(new Throwable(response.getMessage()));
}
}
})
The solution is to add an operator in the middle. My suggestion is to use map
as it does not generate new Observable
object (in comparison to flatMap
which does it):
.map(new Func1<Response, Response>() {
@Override
public Response call(Response response) {
if (response.isSuccess()) {
return response;
} else {
throw new Throwable(reponse.getMessage()));
}
}
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.