I usually use singleton pattern with following structure :
first define ServiceHelper
like following :
public class ServiceHelper {
private static final String ENDPOINT = "http://test.com";
private static OkHttpClient httpClient = new OkHttpClient();
private static ServiceHelper instance = new ServiceHelper();
private IPlusService service;
private ServiceHelper() {
Retrofit retrofit = createAdapter().build();
service = retrofit.create(IPlusService.class);
}
public static ServiceHelper getInstance() {
return instance;
}
private Retrofit.Builder createAdapter() {
httpClient.setReadTimeout(60, TimeUnit.SECONDS);
httpClient.setConnectTimeout(60, TimeUnit.SECONDS);
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
httpClient.interceptors().add(interceptor);
return new Retrofit.Builder()
.baseUrl(ENDPOINT)
.client(httpClient)
.addConverterFactory(GsonConverterFactory.create());
}
public Call<List<CategoryModel>> getAllCategory() {
return service.getAllCategory();
}
Then put all of your services in IService
(in my case it’s IPlusService
)
public interface IPlusService {
//@Headers( "Content-Type: application/json" ) in Post method may use this
@GET("/api/category")
Call<List<CategoryModel>> getAllCategory();
}
Then call your singleton like below in your activity/fragment :
ServiceHelper.getInstance().getAllCategory().enqueue(new Callback<List<CategoryModel>>() {
@Override
public void onResponse(Response<List<CategoryModel>> response, Retrofit retrofit) {
processResponse(response);
}
@Override
public void onFailure(Throwable t) {
processResponse(null);
}
});