Skip to content

Instantly share code, notes, and snippets.

@tylerjroach
Created September 28, 2016 17:23
Show Gist options
  • Save tylerjroach/23a363cc3dcd11108ef25e0b7abbab82 to your computer and use it in GitHub Desktop.
Save tylerjroach/23a363cc3dcd11108ef25e0b7abbab82 to your computer and use it in GitHub Desktop.
Retrofit Singleton Example
package com.tylerjroach.example.retrofit2;
import com.tylerjroach.example.BuildConfig;
import com.tylerjroach.example.util.Constants;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit.RestAdapter;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class Retrofit2Client {
private static Retrofit2Client instance = null;
private Retrofit retrofit;
private OkHttpClient client;
private ExploreService exploreService;
public Retrofit2Client() {
HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();
okHttpBuilder.addInterceptor(new TokenInterceptor());
if (BuildConfig.DEBUG) {
okHttpBuilder.addInterceptor(loggingInterceptor);
}
client = okHttpBuilder.build();
retrofit = new Retrofit.Builder().baseUrl(Constants.API_URL)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
exploreService = retrofit.create(ExploreService.class);
}
public static Retrofit2Client getInstance() {
if (instance == null) {
instance = new Retrofit2Client();
}
return instance;
}
public ExploreService getExploreService() {
return exploreService;
}
}
@Tgo1014
Copy link

Tgo1014 commented Mar 26, 2018

Thank you

@nujnay
Copy link

nujnay commented Nov 6, 2018

is it better to use weakreference?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment