How to use Fuel with a Kotlin coroutine

回眸只為那壹抹淺笑 提交于 2019-12-30 11:10:12

问题


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()
}

But that is returning an android.os.NetworkOnMainThreadException. The Fuel documentation mentions .await() and .awaitString() extensions but I haven't figured it out.

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...


回答1:


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.

I've studied Fuel's test code:

Fuel.get("/uuid").awaitStringResponse().third
    .fold({ data ->
        assertTrue(data.isNotEmpty())
        assertTrue(data.contains("uuid"))
    }, { error ->
        fail("This test should pass but got an error: ${error.message}")
    })

This should be enough to get you going. For example, you might write a simple function as follows:

suspend fun getToken() = TOKEN_URL.httpGet().awaitStringResponse().third



回答2:


From the documentation "to start a coroutine, there must be at least one suspending function, and it is usually a suspending lambda"

Try this:

async {
    val token = getToken()
    println(token)
}


来源:https://stackoverflow.com/questions/50402433/how-to-use-fuel-with-a-kotlin-coroutine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!