How to make a singleton for retrofit 2?

后端 未结 5 616
别跟我提以往
别跟我提以往 2021-01-20 18:40

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

5条回答
  •  梦毁少年i
    2021-01-20 19:00

    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();
    

提交回复
热议问题