Home > database >  Kotlin: How to return a value from a lambda to a parent function?
Kotlin: How to return a value from a lambda to a parent function?

Time:08-08

How can I return String(bytes) to getPost function, so I can println(getPost(123)) and it would print the value of 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)

                }
            }
       

    }

CodePudding user response:

The API you're using is an asynchronous API, and it's callback-based. This means the lambda you have here is run asynchronously and may not have been run yet when your getPost function returns. It is therefore not possible to get its result when returning from 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. There is an additional module for Fuel that you can use to do exactly that: https://fuel.gitbook.io/documentation/support/fuel-coroutines

  • Related