Search code examples
androidkotlincallbackandroid-asynctaskcompletionhandler

Completion Handler Android Kotlin


I'm sorry if this question has been asked previously, I really couldn't find anything even similar! I'm also sorry if the question is dumb, I'm an iOS Developer and I'm a bit lost here in Android...

So I'm using Fuel Library to GET JSON data from an API... In Swift there's something called "completion handler" that whenever the function finishes, it will return it and immediately run the code inside it. This is an example in Swift:

func hardProcessingWithString(input: String, completion: (result: String) -> Void) {
    ...
    completion("we finished!")
}

What I need is to do something similar with this following function that I have in Kotlin.

fun recomendationsData() {

    Fuel.get("https://rss.itunes.apple.com/api/v1/us/apple-music/hot-tracks/10/explicit.json").response { request, response, result ->
                    println(request)
                    println(response)
                    val (bytes, error) = result
                    if (bytes != null) {
                        val str = String(bytes)
                        val obj = JSONObject(str)
                        val resultsP = obj.getJSONObject("feed")
                        val results = resultsP.getJSONArray("results")

                        for (i in 0..(results.length() - 1)) {
                            val o = results.getJSONObject(i)
                            trackName1.add(o.getString("name"))
                            trackArtist1.add(o.getString("artistName"))
                            trackImage1.add(o.getString("artworkUrl100"))
                        }
                    }
                }
}

I've read about something called "callback" but I really don't understand how it works, nor how to implement it (The task must be done Asynchronously).


Solution

  • In this case the syntax is similar to swift:

    fun recommendationsData(callback: (String) -> Unit) {
    

    Then in your function you have a function called callback that you can call with the result (change String to whatever you're returning).

    Then change your function invocation from recommendationsData() to either recommendationsData(doSomething) or

    recommendationsData {
        doSomethingWith(it) // or you can get named argument
        // do some more stuff
    }