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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With