Skip to content

Instantly share code, notes, and snippets.

@henriquehorbovyi
Created July 8, 2020 17:59
Show Gist options
  • Save henriquehorbovyi/1530a578c45c94a76e225327ab3b4805 to your computer and use it in GitHub Desktop.
Save henriquehorbovyi/1530a578c45c94a76e225327ab3b4805 to your computer and use it in GitHub Desktop.
Service Builder for Retrofit
/**
* .:.:.:. Created on 07/10/19 .:.:.:.
*/
interface ServiceBuilder {
companion object {
inline operator fun <reified S> invoke(baseUrl: String, authToken: String? = ""): S {
val httpClient = buildInterceptors(authToken)
return Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.client(httpClient)
.build()
.create(S::class.java)
}
fun buildInterceptors(authToken: String?): OkHttpClient {
val loggerInterceptor = getLoggerInterceptor()
val authInterceptor = AuthenticationInterceptor(authToken)
return OkHttpClient.Builder().apply {
addInterceptor(loggerInterceptor)
if (!interceptors().contains(authInterceptor)) addInterceptor(authInterceptor)
}.build()
}
private fun getLoggerInterceptor(): HttpLoggingInterceptor {
val level = if (BuildConfig.DEBUG)
HttpLoggingInterceptor.Level.BODY
else
HttpLoggingInterceptor.Level.NONE
return HttpLoggingInterceptor().apply { this.level = level }
}
}
}
/**
* Sample: ServiceBuilder<UserService>()
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment