Skip to content

Instantly share code, notes, and snippets.

@omarzer0
Last active January 10, 2022 13:08
Show Gist options
  • Save omarzer0/a5c8c9ca296bf14d8c39e9382449e233 to your computer and use it in GitHub Desktop.
Save omarzer0/a5c8c9ca296bf14d8c39e9382449e233 to your computer and use it in GitHub Desktop.
Service interceptor to update any okHttp/Retrofit header during run time when using hilt
@Singleton
class MyServiceInterceptor @Inject constructor(
private var sessionToken: String = ""
) : Interceptor {
fun setSessionToken(sessionToken: String) {
this.sessionToken = sessionToken
}
override fun intercept(chain: Interceptor.Chain): Response {
val request: Request = chain.request()
val requestBuilder: Request.Builder = request.newBuilder()
if (request.header("No-Authentication") == null) {
if (sessionToken.isNotEmpty()) {
requestBuilder.addHeader("Authorization", "brear $sessionToken")
}
}
return chain.proceed(requestBuilder.build())
}
}
// use it in retrofit module
@Provides
@Singleton
fun provideOkHttpClient(
loggingInterceptor: HttpLoggingInterceptor,
interceptor: MyServiceInterceptor
): OkHttpClient {
return OkHttpClient().newBuilder().apply {
callTimeout(timeOut, TimeUnit.SECONDS)
connectTimeout(timeOut, TimeUnit.SECONDS)
readTimeout(timeOut, TimeUnit.SECONDS)
writeTimeout(timeOut, TimeUnit.SECONDS)
addInterceptor(interceptor)
addInterceptor(loggingInterceptor)
}.build()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment