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 ?
To return values, we use the return keyword. In the example, we have two square functions. When a funcion has a body enclosed by curly brackets, it returns a value using the return keyword. The return keyword is not used for functions with expression bodies.
Kotlin's approach to working with asynchronous code is using coroutines, which is the idea of suspendable computations, i.e. the idea that a function can suspend its execution at some point and resume later on.
To wait for a coroutine to finish, you can call Job. join . join is a suspending function, meaning that the coroutine calling it will be suspended until it is told to resume. At the point of suspension, the executing thread is released to any other available coroutines (that are sharing that thread or thread pool).
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With