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()
)
}
One of the most important points to remember about the suspend functions is that they are only allowed to be called from a coroutine or another suspend function.
I am referring to the suspend keyword. It is not the same as async.
Coroutines can suspend themselves, and the dispatcher is responsible for resuming them. To specify where the coroutines should run, Kotlin provides three dispatchers that you can use: Dispatchers. Main - Use this dispatcher to run a coroutine on the main Android thread.
Hunting to know BLOCKING vs SUSPENDINGA process is blocked when there is some external reason that it can not be restarted, e.g., an I/O device is unavailable, or a semaphore file is locked. A process is suspended means that the OS has stopped executing it, but that could just be for time-slicing (multitasking).
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.
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