在普通函数中调用暂停函数 [英] call a suspend function inside a normal function
本文介绍了在普通函数中调用暂停函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在普通函数中调用阻止暂停函数,但不阻止线程完成暂停函数,然后返回 Response
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()
)
}
推荐答案
这似乎是在实现OkHttp拦截器,所以我希望 intercept()
This looks like you are implementing an OkHttp interceptor, so I am hoping that intercept()
is being called on a background thread.
如果是这样,使用 runBlocking()
:
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()
将执行 suspend
函数,阻塞当前线程,直到该工作完成。
runBlocking()
will execute the suspend
function, blocking the current thread until that work is complete.
这篇关于在普通函数中调用暂停函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文