I usually created a Retrofit client in the App class in onCreate (), but I heard the opinion that this is wrong, because in fact it turns out that this is not Singleton. Where and how best to create a Retrofit client?

My sample code is:

public class App extends Application { public static MessengerApi service; private static OkHttpClient client; private static Retrofit retrofit; @Override public void onCreate() { super.onCreate(); HeaderInterceptor headerInterceptor = new HeaderInterceptor(); HttpLoggingInterceptor logger = new HttpLoggingInterceptor(); logger.setLevel(HttpLoggingInterceptor.Level.BODY); client = new OkHttpClient.Builder() .connectTimeout(60, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .addInterceptor(logger) .addInterceptor(headerInterceptor) .build(); retrofit = new Retrofit.Builder() .baseUrl(BuildConfig.BASE_URL) .client(client) .addConverterFactory(GsonConverterFactory.create()) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .build(); service = retrofit.create(MessengerApi.class); } } 
  • one
    And why is he not a singleton? He is a singleton. It is created once at the start of the application. App calls to OnCreate once - pavel163

2 answers 2

I create a retrofit in BaseApiManager

  public BaseApiManager(final String baseUrl) { final Context ctx = IsoverApplication.getInstance(); mMainHandler = new WeakHandler(ctx.getMainLooper()); final HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(); interceptor.setLevel(HttpLoggingInterceptor.Level.BODY); final OkHttpClient.Builder builder = new OkHttpClient.Builder().addInterceptor(new BasicAuthInterceptor("isover", "isover2016")) .cookieJar(new MemoryCookieJar()) .addInterceptor(new EmptyBodyToJsonInterceptor()) .addNetworkInterceptor(interceptor); builder.cache(new Cache(ctx.getCacheDir(), SIZE_OF_CACHE)) .interceptors() .addAll(getAdditionalInterceptors()); mClient = builder.build(); mRetrofit = new Retrofit.Builder().baseUrl(baseUrl) .client(mClient) .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .addConverterFactory(new ToStringConverterFactory()) .addConverterFactory(createConverterFactory()) .callbackExecutor(Executors.newCachedThreadPool()) .build(); } 

,

which is singleton

  public static BaseApiManager getInstance() { if (sInstance == null) { sInstance = new BaseApiManager(); } return sInstance; } 

getInstance () I pull on every request, i.e. A retrofit can be created every time, for each request.

    You do everything right, in Application it is the place, but I would not advise storing the state in static variables, there are different opinions on this. I would also recommend using dagger for this purpose.