So when I make a POST API call to my server, I get a 400 Bad Request error with JSON response.
{
\"userMessage\": \"Blah\",
\"internalMessage\": \"Bad Re
I got similar issue, but existing code was stick to RxJava 2 chain. Here's my solution:
public static Observable rxified(final Call request, final Class klazz) {
return Observable.create(new ObservableOnSubscribe() {
AtomicBoolean justDisposed = new AtomicBoolean(false);
@Override
public void subscribe(final ObservableEmitter emitter) throws Exception {
emitter.setDisposable(new Disposable() {
@Override
public void dispose() {
request.cancel();
justDisposed.set(true);
}
@Override
public boolean isDisposed() {
return justDisposed.get();
}
});
if (!emitter.isDisposed())
request.enqueue(new Callback() {
@Override
public void onResponse(Call call, retrofit2.Response response) {
if (!emitter.isDisposed()) {
if (response.isSuccessful()) {
emitter.onNext(response.body());
emitter.onComplete();
} else {
Gson gson = new Gson();
try {
T errorResponse = gson.fromJson(response.errorBody().string(), klazz);
emitter.onNext(errorResponse);
emitter.onComplete();
} catch (IOException e) {
emitter.onError(e);
}
}
}
}
@Override
public void onFailure(Call call, Throwable t) {
if (!emitter.isDisposed()) emitter.onError(t);
}
});
}
});
}
transforming 400-like responses into rx chain is pretty simple:
Call request = catApi.getCat();
rxified(request, Cat.class).subscribe( (cat) -> println(cat) );