简体   繁体   English

Kotlin:如何从异步lambda中返回变量?

[英]Kotlin: How to return a variable from within an asynchronous lambda?

I'm using fuel http to make a simple GET request. 我正在使用Fuel http发出简单的GET请求。 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 . 如果我确实在val tweets之下return tweets ,则会收到错误消息: 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? 但是问题仍然存在,我该如何编写一个函数以返回在lambda中创建的变量? In this case, I want to return tweets 在这种情况下,我想返回tweets

You could pass a lambda to your method: 您可以将lambda传递给您的方法:

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): 使用https://github.com/kittinunf/fuel/tree/master/fuel-coroutines,您应该可以编写如下内容(我不熟悉该库,这仅基于README示例):

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() ?) (不清楚您的问题中c来源;这可能是result.get().toList()的错字吗?)

If you are unfamiliar with coroutines, read https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html . 如果您不熟悉协程,请阅读https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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