Reputation: 5724
I want to call blocking a suspend function in a normal function, but does not block Thread to finishing suspend function and then return Response
override fun intercept(chain: Interceptor.Chain): Response {
// getSession is a suspend function
val session = sessionProvider.getSession()
return chain.proceed(
chain
.request()
.newBuilder()
.addHeader("Authorization", "${session.token}")
.build()
)
}
Upvotes: 34
Views: 18382
Reputation: 1006674
This looks like you are implementing an OkHttp interceptor, so I am hoping that intercept()
is being called on a background thread.
If so, use runBlocking()
:
override fun intercept(chain: Interceptor.Chain): Response {
// getSession is a suspend function
val session = runBlocking { sessionProvider.getSession() }
return chain.proceed(
chain
.request()
.newBuilder()
.addHeader("Authorization", "${session.token}")
.build()
)
}
runBlocking()
will execute the suspend
function, blocking the current thread until that work is complete.
Upvotes: 70