Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ?

like image 847
omer tamir Avatar asked Aug 17 '17 07:08

omer tamir


People also ask

How do I return a value to Kotlin?

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.

Are coroutines asynchronous Kotlin?

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.

How do you wait for a function to finish in Kotlin?

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).


1 Answers

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.)

like image 156
Christian Brüggemann Avatar answered Sep 18 '22 02:09

Christian Brüggemann