Skip to content Skip to sidebar Skip to footer

Divide Retrofit Service Declaration Into Multiple Interfaces

I am creating an app linking to an API with about 265 methods to it. I would very much like to break apart the declaration of these APIs into multiple files to keep them organized

Solution 1:

Just create separate interfaces.

publicinterfaceProfileService {

  /* ... */
}

publicinterfaceAccountService {

  /* ... */
}

ProfileService profileService = mRestAdapter.create(ProfileService.class);
AccountService accountService = mRestAdapter.create(AccountService.class);

Solution 2:

I am still experimenting on if this is the best way to go about using this but here is what I have so far. It may not be the cleanest approach yet but I am liking it versus one service with 100 api calls. Splits it up a little and makes it easier to read.

This is the main class to access the data. I have seen a lot separate out the two static methods I have into a separate class but i just included it as one.

publicclassRetrofitApi {
   publicenumApiTypes {
        USER_API(UserApi.class);

        private final Class<? extendsRetrofitApi> apiClass;
        ApiTypes(Class<? extendsRetrofitApi> apiClass){
            this.apiClass = apiClass;
        }
        Class<? extendsRetrofitApi> getApiType() {returnthis.apiClass;}
    }
    publicstatic  <T> T getApi(RetrofitApi.ApiTypes type) {
        try {
            return (T) type.getApiType().newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        returnnull;
    }
    publicstaticRestAdaptergetRestAdapter() {
        RestAdapter restAdapter = newRestAdapter.Builder()
            .setEndpoint(BASE_URL)
            .setLogLevel(retrofit.RestAdapter.LogLevel.HEADERS)
            .build();
        return restAdapter;
    }
}

Each service has its own api. This does mean more classes. I split them into api, service, model. API is the high level that you will use and expose. Service is more or less just a list of calls. And Model is the model (data object).

publicclassUserApiextendsRetrofitApi {

    private UserService service;

    publicUserApi() {
        RestAdapter restAdapter =
                RetrofitApi.getRestAdapter();
        service = restAdapter.create(UserService.class);
    }

    publicvoidlogin(String email,
                      String password,
                      Callback<User> callback) {
        service.login(email, password, callback);
    }
}

Service is the interface. Its more or less just a list of api calls that get exposed.

publicinterfaceUserService {

    @GET("/api/users/login")
    void login(@Query("email") String email,
                   @Query("password") String password,
                   Callback<User> callback);
}

Then to use it.

UserApiapi= RetrofitApi.getApi(RetrofitApi.ApiTypes.USER_API);
 api.login(email,password,callback);

And here is the project structure. To me, it seems clean at the moment. I am sure it will end up getting big when I have 20+ of them. But it might be a little cleaner when those 20 have multiple calls. enter image description here

Solution 3:

You can try the following.

Create 2 interface class.

  • ARetrofitApi
  • BRetrofitApi

Place Your Calls

// ARetrofitApi@FormUrlEncoded@POST("get_favorite_food/{id}")
Call<JsonObject> getFavoriteFood(@Path("id") String userId,
                          @Field("image") String image,
                          @Field("name") String foodName);

// BRetrofitApi@FormUrlEncoded@POST("get_favorite_sport/{id}")
Call<JsonObject> getFavoriteSport(@Path("id") String userId,
                          @Field("image") String image,
                          @Field("name") String sportName);

In You Builder

privatestatic final String BASE_URL = "http://192.168.1.4/myapp/";

privatestatic RetrofitClient mInstance;
private Retrofit retrofit;

privateRetrofitClient() {

retrofit = new Retrofit.Builder().baseUrl(BASE_URL)
                                     .addConverterFactory(GsonConverterFactory.create())
                                     .build();
}

publicstatic synchronized RetrofitClient getInstance() {
    if (mInstance == null) {
        mInstance = new RetrofitClient();
    }
    return mInstance;
}

public ARetrofitApi aGetApi() {
    return retrofit.create(ARetrofitApi.class);
}

public BRetrofitApi bGetApi() {
    return retrofit.create(BRetrofitApi.class);
}

To Call

// Use RetroFit To Feed To MySQL
Call<JsonObject> call = RetrofitClient.getInstance()
                                  .aGetApi()
                                  .getFavoriteFood(userId,
                                               image,
                                               foodName);

// Use RetroFit To Feed To MySQL
Call<JsonObject> call = RetrofitClient.getInstance()
                                  .bGetApi()
                                  .getFavoriteSport(userId,
                                               image,
                                               sportName);

Post a Comment for "Divide Retrofit Service Declaration Into Multiple Interfaces"