Skip to content Skip to sidebar Skip to footer

How To Use Fuel With A Kotlin Coroutine

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)

Solution 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:

suspendfungetToken() = TOKEN_URL.httpGet().awaitStringResponse().third

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

Post a Comment for "How To Use Fuel With A Kotlin Coroutine"