Issue
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?
Solution
When Response from Server is 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()
Answered By - Milind Mevada
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.