tursunov abdulbois
11/17/2021, 2:20 PM@Singleton
class AuthenticationInterceptor @Inject constructor(profileRepository: ProfileRepository, @ApplicationScope coroutineScope: CoroutineScope) :
Interceptor {
private val tokenFlow: Flow<String?> = profileRepository.getProfileToken()
.stateIn(coroutineScope, SharingStarted.Eagerly, null)
override fun intercept(chain: Interceptor.Chain): Response {
val requestBuilder = chain.request().newBuilder()
val token: String? = runBlocking { // this line should be changed
tokenFlow.firstOrNull()
}
token?.let { requestBuilder.addHeader("Authorization", it) }
return chain.proceed(requestBuilder.build())
}
}
Casey Brooks
11/17/2021, 7:39 PMrunBlocking
exists for exactly this reason, to use coroutine-based code within a thread-blocking context.
OkHttp interceptors use a blocking API, not a callback-based one, so this is a perfectly legitimate use-case for runBlocking
. As long as the entire request is being run on background threads (<http://Dispatchers.IO|Dispatchers.IO>
for example), then you'll only block that one background thread, but not impact anything else