Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle No Content response using RxJava2 et Retrofit2

I'm using RxJava 2 & Retrofit 2 (https://github.com/JakeWharton/retrofit2-rxjava2-adapter) and I was wondering how to handle no response (204) type. In rxjava1 i was using Observable<Void> but it's not allowed by rxjava2 anymore (https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0 -> Nulls)

Right now, i've hacked around to bypass Json parsing on a custom type (I called it NoContent) but I was wondering if there is a better way.

EDIT:

public class NoContent {
    public static class GsonTypeAdapter extends TypeAdapter<NoContent> {

        @Override
        public void write(JsonWriter out, NoContent value) throws IOException {
           out.nullValue();
        }

        @Override
        public NoContent read(JsonReader in) throws IOException {
           return new NoContent();
        }
    }
}
like image 342
Romain Avatar asked Oct 29 '22 16:10

Romain


1 Answers

You can use Completable, Observable<ResponseBody> or Observable<Response<T>> in the case you are going to get 204 responses without getting converter exceptions.

Probably the best option here is to use Completable as return type. All 2xx responses from server will end up in onComplete. Other will end up in onError.

In case of ResponseBody all kind of valid HTTP responses won't be converted to Object and will end up in onNext, including 4xx and 5xx responses.

In case of Response<T> only 2xx responses will be converted, including, probably HTTP 204 response code. So I am not sure you should use it, although all valid HTTP responses in this case will also end up in onNext, including 4xx and 5xx responses.

like image 125
Клаус Шварц Avatar answered Nov 15 '22 06:11

Клаус Шварц