如何与Kotlin协程一起使用Fuel [英] How to use Fuel with a Kotlin coroutine
问题描述
在一个Android应用中,我试图使用燃料在一个Kotlin协程.我的第一个尝试是在这样的包装器内使用同步模式:
Within an Android app, I'm trying to use Fuel to make an HTTP request within a Kotlin coroutine. My first try is to use the synchronous mode inside a wrapper like this:
launch(UI) {
val token = getToken()
println(token)
}
suspend fun getToken(): String? {
var (request, response, result = TOKEN_URL.httpGet().responseString()
return result.get()
}
但是返回的是android.os.NetworkOnMainThreadException
. Fuel文档中提到了.await()和.awaitString()扩展名,但我还没有弄清楚.
But that is returning an android.os.NetworkOnMainThreadException
. The Fuel documentation mentions .await() and .awaitString() extensions but I haven't figured it out.
从Android应用程序的主UI线程在Kotlin协程中发出Fuel http请求的最佳方法是什么?坚持下去-非常感谢...
What is the best way to make a Fuel http request within a Kotlin coroutine from the main UI thread in an Android application? Stuck on this - many thanks...
推荐答案
从suspend fun
调用阻止代码不会自动将其转换为挂起代码.您调用的函数本身必须已经是suspend fun
.但是,正如您已经提到的,Fuel对Kotlin协程具有一流的支持,因此您不必自己编写.
Calling blocking code from a suspend fun
doesn't automagically turn it into suspending code. The function you call must already be a suspend fun
itself. But, as you already noted, Fuel has first-class support for Kotlin coroutines so you don't have to write it yourself.