So I wanted to implement the example of response from the API like in this video droidcon NYC 2017 - Advanced Networking with RxJava + Retrofit
And this is my code:
Presenter.java
compositeDisposable.add(RetrofitClient.createService(GetApi.class)
.getResponseFromServer(token)
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Consumer<ResponseFromServer>() {
@Override
public void accept(ResponseFromServer responseFromServer) throws Exception {
mView.setResponseObject(responseFromServer);
}
}, new Consumer<Throwable>() {
@Override
public void accept(Throwable throwable) throws Exception {
throwable.printStackTrace();
if (throwable instanceof HttpException) {
int responseCode = ((HttpException) throwable).code();
}
}
}));
So here, when I get some 4xx error response from the server, I can go to Throwable
and get the response code, and if response is okay I can get my object, and everything is cool.
However, in the video example above, the guy suggest that I wrap my ResponseFromServer
with Response like this: Single<Response<ResponseFromServer>> getResponseFromServer(@Header("X-Authorize") String token);
so I can access response codes also, but in that case, my Throwable
never gets called, so I can access to the codes only in the first accept method, but in the video he catch the errors in the Throwable
section. So, I cant figure it out what I'm doing wrong? Maybe I'm using the wrong Observer?
When Response from Server is code < 200 || code >= 300
code < 200 || code >= 300
in those cases onError()
will be invoked. and other cases onNext()
will invoke.
Also, If your code from onNext()
throws any exception, that will be catch in onError()
I think i figured it out, if we wrap our response object with Observable<Response<Object>>
all of the response code will be caught in the regular accept method, so we kinda need to extract the codes manually and do the checks. However, if we keep the Observable<Object>
, errorCode < 200 || errorCode > 400 will be caught in the onError method.
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.