Last active
January 10, 2022 13:08
-
-
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
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
@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