If there exists multiple retrofit call, how can i make a singleton of a retrofit, so that there won\'t be repeated codes within the class, thereby get rid of unnecessary cod
Here's an example, but! Although this might be shiny and easy to use, singletons are evil. Try to avoid using them if possible. One way around it is by using dependency injection instead.
Anyway.
public class Api {
private static Api instance = null;
public static final String BASE_URL = "your_base_url";
// Keep your services here, build them in buildRetrofit method later
private UserService userService;
public static Api getInstance() {
if (instance == null) {
instance = new Api();
}
return instance;
}
// Build retrofit once when creating a single instance
private Api() {
// Implement a method to build your retrofit
buildRetrofit(BASE_URL);
}
private void buildRetrofit() {
Retrofit retrofit = ...
// Build your services once
this.userService = retrofit.create(UserService.class);
...
}
public UserService getUserService() {
return this.userService;
}
...
}
Now you have everything in one place. Use it.
UserService userService = Api.getInstance().getUserService();