Android - Kotlin : return value in async fun

11,406

Solution 1

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

Solution 2

Not only in kotlin, this is not possible in any programming language to return from a async method. But what you can do is :

  1. Use co-routines like Christian suggested.
  2. 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.
  3. If you are doing very simple things, Callbacks can be helpful.
Share:
11,406

Related videos on Youtube

omer tamir
Author by

omer tamir

Updated on June 04, 2022

Comments

  • omer tamir
    omer tamir about 2 years

    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 ?

  • DarkCygnus
    DarkCygnus about 6 years
    I think you missed the parentheses surrounding the callback parameter Int: fun readData(callback: (Int) -> Unit), otherwise Android Studio gives warning error (editing)