简体   繁体   中英

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

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

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM