nz_21
nz_21

Reputation: 7403

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<Tweet> {

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

If I do return tweets just below val tweets, I get an error: return is not allowed here.

The makes sense to me. But the question still remains, how do I write a function that returns the variable created within the lambda? In this case, I want to return tweets

Upvotes: 0

Views: 644

Answers (2)

Alexey Romanov
Alexey Romanov

Reputation: 170919

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

suspend fun fetchTweets(): 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.

Upvotes: 1

Francesc
Francesc

Reputation: 29380

You could pass a lambda to your method:

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

Upvotes: 1

Related Questions