I'm trying to implement JWT token authentication and refresh token in retrofit using coroutines. The tokens are stored in a Room database. How should I implement the await call?
Currently I'm using runBlocking {...} call to wait for the async local/remote response
Example:
client.addInterceptor {
val accessToken = runBlocking { tokenRepository.getActiveToken() }?.access_token ?: "-"
val request = it.request()
.newBuilder()
.addHeader("Authorization", "Bearer $accessToken")
.build()
return@addInterceptor it.proceed(request)
}
What I'd like to follow is the traditional pattern of:
launch {
withContext(IO){...}
}
How should I go about it?
OkHttp is a Java library and uses synchronous request interceptors. Kotlin's coroutines aren't able to transform sync code into async, they just make your already async code look as simple as sync code. There was already a feature request in OkHttp to enable specifically what you ask for, but was declined. The reason is that, from the Java perspective, it makes a mess of the API and the implementation complexity is also very high.
Their recommendation is to handle this outside OkHttp, so in your case to first fetch the token in an async way and then initiate the HTTP request.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With