I\'m consuming an API from my android app, and all the JSON responses are like this:
{
\'status\': \'OK\',
\'reason\': \'Everything was fine\',
\
Had the same problem couple of days ago. I've solve this using response wrapper class and RxJava transformer, which I think is quite flexiable solution:
Wrapper:
public class ApiResponse {
public String status;
public String reason;
public T content;
}
Custom exception to throw, when status is not OK:
public class ApiException extends RuntimeException {
private final String reason;
public ApiException(String reason) {
this.reason = reason;
}
public String getReason() {
return apiError;
}
}
Rx transformer:
protected Observable.Transformer, T> applySchedulersAndExtractData() {
return observable -> observable
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.map(tApiResponse -> {
if (!tApiResponse.status.equals("OK"))
throw new ApiException(tApiResponse.reason);
else
return tApiResponse.content;
});
}
Example usage:
// Call definition:
@GET("/api/getMyPojo")
Observable> getConfig();
// Call invoke:
webservice.getMyPojo()
.compose(applySchedulersAndExtractData())
.subscribe(this::handleSuccess, this::handleError);
private void handleSuccess(MyPojo mypojo) {
// handle success
}
private void handleError(Throwable t) {
getView().showSnackbar( ((ApiException) throwable).getReason() );
}
My topic: Retrofit 2 RxJava - Gson - "Global" deserialization, change response type