簡體   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