在普通函数中调用挂起函数

call a suspend function inside a normal function

我想在普通函数中调用阻塞挂起函数,但不阻塞线程完成挂起函数然后 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() 在后台线程上被调用。

如果是,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 函数,阻塞当前线程直到该工作完成。