【问题标题】:Kotlin: How to return a variable from within an asynchronous lambda?Kotlin:如何从异步 lambda 中返回变量?
【发布时间】:2019-02-17 22:06:45
【问题描述】:

我正在使用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

【问题讨论】:

    标签: android kotlin concurrency functional-programming


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      使用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

      【讨论】:

        猜你喜欢
        • 2021-12-22
        • 2016-11-25
        • 1970-01-01
        • 2018-01-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-02-22
        • 1970-01-01
        相关资源
        最近更新 更多