How to get a value from inside Anko's async? (KotlIn)

168 views Asked by At

I have a function which uses Anko's async in order to call Google's Distance API and get the distance from one location to another. unfortunately i don't know how to get the data from inside the async and pass it to another function. the code looks something like this

fun getDistance(location1:LatLng,location2:LatLng){
    async{
        val result = URL(url).readtext() 
        uithread{
            //Parser
            //distance value
        }
    }
}

I'd like to also mention im really new to kotlin or android development in general, please be kind.

1

There are 1 answers

0
Joozd On

There are a number of ways to tackle this; pass an object to the function with your array in it that gets rearranged in your function, or go with something like:

fun getDistance(location1 : LatLng, location2 : LatLng, f: (Long) -> Unit){
    doAsync{ // Anko is deprecated as I have been made aware
        val result = URL(url).readtext()
        val distance : Long = // parse result
        uiThread{
            f(distance)
        }
    }
}

and call that with

getDistance(loc1, loc2) { toast("The found distance was $it") }

This is by no means the only way to go; you could update a larger-scoped variable, call a listener, put your lat-longs in a class with updating functions that are called, or a bunch of other ways that I am too lazy to think about :)