Created
July 8, 2020 17:59
-
-
Save henriquehorbovyi/1530a578c45c94a76e225327ab3b4805 to your computer and use it in GitHub Desktop.
Service Builder for Retrofit
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
/** | |
* .:.:.:. 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