繁体   English   中英

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

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

我正在使用Fuel http发出简单的GET请求。 这是我的代码:

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

如果我确实在val tweets之下return tweets ,则会收到错误消息: return is not allowed here

这对我来说很有意义。 但是问题仍然存在,我该如何编写一个函数以返回在lambda中创建的变量? 在这种情况下,我想返回tweets

您可以将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)
            }
}

使用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()
}

(不清楚您的问题中c来源;这可能是result.get().toList()的错字吗?)

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

暂无
暂无

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

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