简体   繁体   English

Kotlin:如何将值从 lambda 返回到父 function?

[英]Kotlin: How to return a value from a lambda to a parent function?

How can I return String(bytes) to getPost function, so I can println(getPost(123)) and it would print the value of String(bytes)?如何将String(bytes)返回到 getPost function,这样我就可以println(getPost(123))并打印 String(bytes) 的值?

fun getPost(id: Int) {
        Fuel.get("https://kitsu.io/api/edge/posts/$id")
            .response { request, response, result ->
                val(bytes, error) = result
                if(bytes != null) {
                    println(String(bytes)) 
                    //I want to return String(bytes)

                }
            }
       

    }

The API you're using is an asynchronous API, and it's callback-based.您使用的 API 是异步 API,它是基于回调的。 This means the lambda you have here is run asynchronously and may not have been run yet when your getPost function returns.这意味着您在此处拥有的 lambda 是异步运行的,并且当您的getPost function 返回时可能尚未运行。 It is therefore not possible to get its result when returning from getPost .因此,从getPost返回时无法获得其结果。

To handle this kind of cases in a synchronous-like approach while retaining the benefits of async execution, you could use suspend functions and Kotlin coroutines.要以类似同步的方式处理这种情况,同时保留异步执行的好处,您可以使用suspend函数和 Kotlin 协程。 There is an additional module for Fuel that you can use to do exactly that: https://fuel.gitbook.io/documentation/support/fuel-coroutines Fuel还有一个额外的模块可以用来做这 件事:https://fuel.gitbook.io/documentation/support/fuel-coroutines

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

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