Skip to content

Instantly share code, notes, and snippets.

@philipborbon
Created May 20, 2019 08:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save philipborbon/c77b7fd2fbd7ae33cb8fdf80013f3926 to your computer and use it in GitHub Desktop.
Save philipborbon/c77b7fd2fbd7ae33cb8fdf80013f3926 to your computer and use it in GitHub Desktop.
Retrofit Singleton Factory
companion object Factory {
@Volatile
private var retrofit : Retrofit? = null
@Synchronized
fun getInstance(baseUrl: String, tokenStorage: TokenStorage): FireResponseService? {
retrofit = retrofit ?: synchronized(this) {
retrofit ?: buildRetrofit(baseUrl, tokenStorage)
}
return retrofit?.create(FireResponseService::class.java)
}
private fun buildRetrofit(baseUrl: String, tokenStorage: TokenStorage): Retrofit {
val httpClientBuilder = OkHttpClient.Builder()
val gsonBuilder = GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
val builder = Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create(gsonBuilder.create()))
if (BuildConfig.DEBUG) {
val loggingInterceptor = HttpLoggingInterceptor()
loggingInterceptor.level = HttpLoggingInterceptor.Level.HEADERS
loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
httpClientBuilder.addInterceptor(loggingInterceptor)
}
httpClientBuilder.addInterceptor { chain ->
val request = chain.request()
val requestBuilder = request.newBuilder()
.header("Authorization", tokenStorage.getAuthorization().authorization)
chain.proceed(requestBuilder.build())
}
builder.client(httpClientBuilder.build())
return builder.build()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment