How to use Fuel with a Kotlin coroutine

后端 未结 2 859
失恋的感觉
失恋的感觉 2021-01-13 17:34

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:

相关标签:
2条回答
  • 2021-01-13 18:13

    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)
    }
    
    0 讨论(0)
  • 2021-01-13 18:39

    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
    
    0 讨论(0)
提交回复
热议问题