Android - Kotlin : return value in async fun
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.)
Not only in kotlin
, this is not possible in any programming language to return from a async method
. But what you can do is :
- Use
co-routines
like Christian suggested. - Use Reactive approach like
RxJava or RxKotlin
and deal with stream of data where even though you can not return from your method in different thread, you can observe return type of the function from different thread. - If you are doing very simple things,
Callbacks
can be helpful.