Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

How to Set Up Retrofit With RxJava and Gson

DZone's Guide to

How to Set Up Retrofit With RxJava and Gson

This quick guide to setting up Retrofit for Android mobile development will help you set up an API interface and deserializer.

· Mobile Zone ·
Free Resource

To get started, you need to include the following in your build.gradle file:

    compile 'io.reactivex.rxjava2:rxandroid:2.0.1'
    compile 'io.reactivex.rxjava2:rxjava:2.0.2'
    compile 'com.squareup.retrofit2:retrofit:2.3.0'
    compile 'com.squareup.retrofit2:converter-gson:2.3.0'
    compile 'com.jakewharton.retrofit:retrofit2-rxjava2-adapter:1.0.0'

Now you can set up your API interface with RxJava Observables, for example:

public interface MyAPI {

    @GET("some_json")
    Observable<JsonObject> getJson(@Header("header1") String header1);


    @GET("my_user")
    Observable<User> getUserInfo();
}

As you can see above, I can use my own data model and the JSON response will be converted automatically. I can also simply get a JsonObject if I just want to use the JSON myself.

Alternatively, I can set up my own deserializer, like so:

public class UserDeserializer implements JsonDeserializer<User> {

    @Override
    public User deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        User user = new User();
        // custom parsing logic goes here
        return user;
    }
}

Lastly, here is my API creation with a deserializer for the User added in:

public final class MyAPIBuilder {

    private static final String BASE_URL = "https://MySuperGreatAPI.com/";

    private static MyAPI sMyAPI;

    private MyAPIBuilder() {
    }

    public static MyAPI getMyAPI() {
        init();
        return sMyAPI;
    }

    private static void init() {
        if (sMyAPI == null) {
            Gson gson = new GsonBuilder().registerTypeAdapter(User.class, new UserDeserializer()).create();
            Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl(BASE_URL)
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .build();

            sMyAPI = retrofit.create(MyAPI.class);
            //If you break up your API into different interfaces you can initialize them all here.
        }
    }

}

There are many different ways you can use RetrofitRxJava, and Gson. This example can be used as a starting point, but there is much more you can do with each of these libraries if you need to.

Topics:
android ,mobile ,mobile app development ,retrofit

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}