在普通函数中调用暂停函数

bei*_*rad 2 android suspend coroutine kotlin kotlin-coroutines

我想在普通函数中调用阻止暂停函数,但不阻止线程完成暂停函数,然后返回 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()
    )
}
Run Code Online (Sandbox Code Playgroud)

Com*_*are 8

看起来您正在实现OkHttp拦截器,所以我希望intercept()在后台线程上调用它。

如果是这样,请使用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()
    )
}
Run Code Online (Sandbox Code Playgroud)

runBlocking()将执行该suspend函数,阻塞当前线程,直到该工作完成。