I need to add freshCsrf string to each request into form body. Uses OkHttpClient with AuthInterceptor. The problem is how to send request inside interceptor in order to get the freshCsrf string?
In code below occurs error
Suspend function 'getAuth' should be called only from a coroutine or another suspend function
class AuthInterceptor(val authApi: IAuthService) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
var request = chain.request()
val freshCsrf = authApi.getAuth().freshCsrf
// ... add freshCsrf to form body
return chain.proceed(request)
}
}
// Retrofit service
interface IAuthApi {
@GET("/auth")
suspend fun getAuth(): Auth
}
I try to use coroutine, but also failed because can't wait result. One of example with async/await case ended with error
Suspend function 'await' should be called only from a coroutine or another suspend function
private val scope = CoroutineScope(Dispatchers.IO)
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val freshCsrf = scope.async { authApi.getAuth().freshCsrf }
freshCsrf.await()
// ... add freshCsrf to form body
return chain.proceed(request)
}
Update 1
I confused with runBlocking description
It is designed to bridge regular blocking code to libraries that are written in suspending style, to be used in main functions and in tests.
In one side, retrofit interface is suspending and I need to wait network result in order to continue creating other request (bridge - ok). But in the other side, it isn't main function or test. And many tutorials and articles tell that must to avoid runBlocking in production code. Can you explain it?
override fun intercept(chain: Interceptor.Chain): Response {
val request = chain.request()
val freshCsrf = runBlocking {
return@runBlocking authApi.getAuth().freshCsrf
}
// ... add freshCsrf to form body
return chain.proceed(request)
}
from How to wait result of suspend function?
No comments:
Post a Comment