omer tamir omer tamir - 11 months ago 117
Android Question

Android - Kotlin : return value in async fun

I would like to ask if it's possible to 'return' a value from a function
if the function doing AsyncTask?

For example :

fun readData() : Int{
val num = 1;
doAsync {
for (item in 1..1000000){
num += 1;
}
}
return num;
}


The problem in this function is that the AsyncTask is not finish yet so i get a wrong value from the function ,any idea how to solve it?

is using a interface is the only why or there is a compilation handler like in Swift ?

Answer Source

If you perform some calculation asynchronously, you cannot directly return the value, since you don't know if the calculation is finished yet. You could wait it to be finished, but that would make the function synchronous again. Instead, you should work with callbacks:

fun readData(callback: Int -> Unit) {
    val num = 1
    doAsync { 
        for (item in 1..1000000){
            num += 1
        }
        callback(num)
    }
}

And at callsite:

readData { num -> [do something with num here] }

You could also give Kotlin coroutines a try, which make async code look like regular synchronous code, but those may be a little complex for beginners. (By the way, you don't need semicolons in Kotlin.)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download