Kotlin:如何从异步lambda中返回变量? [英] Kotlin: How to return a variable from within an asynchronous lambda?
问题描述
我正在使用加油http 来进行简单的GET请求. 这是我的代码:
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
}
}
如果我在val tweets
下方执行return tweets
,则会收到错误消息:
return is not allowed here
.
If I do return tweets
just below val tweets
, I get an error:
return is not allowed here
.
这对我来说很有意义.但是问题仍然存在,我该如何编写一个函数来返回在lambda中创建的变量?在这种情况下,我想返回tweets
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
推荐答案
使用 https://github.com/kittinunf/fuel/tree/master/fuel-coroutines 您应该能够编写如下内容(我不熟悉该库,这仅基于README示例):
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()
}
(不清楚您的问题中c
的来源;这可能是result.get().toList()
的错字吗?)
(It isn't clear where c
comes from in your question; is that maybe a typo for result.get().toList()
?)
如果您不熟悉协程,请阅读 https://kotlinlang.org /docs/reference/coroutines/coroutines-guide.html .
If you are unfamiliar with coroutines, read https://kotlinlang.org/docs/reference/coroutines/coroutines-guide.html.
这篇关于Kotlin:如何从异步lambda中返回变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!