How to use Fuel with a Kotlin coroutine

2019-02-20 03:30发布

问题:

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