How to make a singleton for retrofit 2?

后端 未结 5 652
别跟我提以往
别跟我提以往 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 18:54

    public class Singleton  {
    
        private static Singleton INSTANCE = null;
    
        // other instance variables can be here
    
        private Singleton() {};
    
        public static Singleton getInstance() {
            if (INSTANCE == null) {
                INSTANCE = new Singleton();
            }
            return(INSTANCE);
        }
    
        // other instance methods can follow 
    }
    
    
    
    import retrofit2.Retrofit;
    import retrofit2.converter.gson.GsonConverterFactory;
    
    public class RetrofitClient {
    
        private static Retrofit retrofit = null;
    
        public static Retrofit getClient(String baseUrl) {
            if (retrofit==null) {
                retrofit = new Retrofit.Builder()
                        .baseUrl(baseUrl)
                        .addConverterFactory(GsonConverterFactory.create())
                        .build();
            }
            return retrofit;
        }
    }
    
    
    
    
    @Module
    public class NetworkModule {
    
        @Provides
        @Singleton
        public Gson gson() {
            GsonBuilder gsonBuilder = new GsonBuilder();
            return gsonBuilder.create();
        }
    
        @Provides
        @Singleton
        public HttpLoggingInterceptor loggingInterceptor() {
            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(
                    message -> Timber.i(message));
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            return interceptor;
        }
    
        @Provides
        @Singleton
        public Cache cache(File cacheFile) {
            return new Cache(cacheFile, 10 * 1000 * 1000); //10MB Cache
        }
    
        @Provides
        @Singleton
        public File cacheFile(@ApplicationContext Context context) {
            return new File(context.getCacheDir(), "okhttp_cache");
        }
    
        @Provides
        @Singleton
        public OkHttpClient okHttpClient(HttpLoggingInterceptor loggingInterceptor, Cache cache) {
            return new OkHttpClient.Builder()
                    .addInterceptor(loggingInterceptor)
                    .cache(cache)
                    .build();
        }
    
        @Provides
        @Singleton
        public Retrofit retrofit(OkHttpClient okHttpClient, Gson gson) {
            return new Retrofit.Builder()
                    .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                    .addConverterFactory(GsonConverterFactory.create(gson))
                    .client(okHttpClient)
                    .baseUrl("you/base/url")
                    .build();
        }
    }
    

提交回复
热议问题