Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)?

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)

                }
            }
       

    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading