Hi, guys. I have AuthtenticationInterceptor to add...
# android
t
Hi, guys. I have AuthtenticationInterceptor to add token into header of request. In overrided intercept function it uses runBlocking builder to get token (token is obtained as flow object. Its repository implements PreferencesDataStore). I should replace runBlocking builder to other proper implementation. Because using runBlocking builder in production code is not good practice. Any sugestions?
Copy code
@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())
    }
}
c
To my knowledge, that's the only way to use coroutines inside an OkHttp interceptor, and it's not a hack.
runBlocking
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
👍 3