Divide Retrofit service declaration into multiple interfaces
Just create separate interfaces.
public interface ProfileService {
/* ... */
}
public interface AccountService {
/* ... */
}
ProfileService profileService = mRestAdapter.create(ProfileService.class);
AccountService accountService = mRestAdapter.create(AccountService.class);
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.
public class RetrofitApi {
public enum ApiTypes {
USER_API(UserApi.class);
private final Class<? extends RetrofitApi> apiClass;
ApiTypes(Class<? extends RetrofitApi> apiClass){
this.apiClass = apiClass;
}
Class<? extends RetrofitApi> getApiType() {return this.apiClass;}
}
public static <T> T getApi(RetrofitApi.ApiTypes type) {
try {
return (T) type.getApiType().newInstance();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return null;
}
public static RestAdapter getRestAdapter() {
RestAdapter restAdapter = new RestAdapter.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).
public class UserApi extends RetrofitApi {
private UserService service;
public UserApi() {
RestAdapter restAdapter =
RetrofitApi.getRestAdapter();
service = restAdapter.create(UserService.class);
}
public void login(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.
public interface UserService {
@GET("/api/users/login")
void login(@Query("email") String email,
@Query("password") String password,
Callback<User> callback);
}
Then to use it.
UserApi api = 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.