Created
May 20, 2019 08:23
-
-
Save philipborbon/c77b7fd2fbd7ae33cb8fdf80013f3926 to your computer and use it in GitHub Desktop.
Retrofit Singleton Factory
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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