Skip to content Skip to sidebar Skip to footer

Kotlin: How To Return A Variable From Within An Asynchronous Lambda?

I'm using fuel http to make a simple GET request. Here's my code: fun fetchTweets(): List { endpoint.httpGet(listOf('user' to 'me', 'limit' to 20)) .resp

Solution 1:

You could pass a lambda to your method:

funfetchTweets(
        callback: (List<Tweet>) -> Unit
) {

    endpoint.httpGet(listOf("user" to "me", "limit" to 20))
            .responseObject(Tweet.Deserializer()) { _, _, result ->
                result.get().forEach { Log.i("TWEET", it.text) }
                val tweets = c.get().toList()
                callback(tweets)
            }
}

Solution 2:

Using https://github.com/kittinunf/fuel/tree/master/fuel-coroutines you should be able to write something like (I am unfamiliar with the library, this is based just on the README example):

suspendfunfetchTweets(): List<Tweet> {

    val (_, _, result) = endpoint.httpGet(listOf("user" to "me", "limit" to 20))
        .awaitObjectResponseResult(Tweet.Deserializer())
    result.get().forEach { Log.i("TWEET", it.text) }
    return c.get().toList()
}

(It isn't clear where c comes from in your question; is that maybe a typo for result.get().toList()?)

If you are unfamiliar with coroutines, read https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html.

Post a Comment for "Kotlin: How To Return A Variable From Within An Asynchronous Lambda?"