0

Kotlin - async vs launch and returning value

 1 year ago
source link: http://mussatto.github.io/kotlin/async/launch/2020/08/14/kotlin-async-vs-launch.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Kotlin - async vs launch and returning value

“Stuff I always forget how to do and have to google it”

The main difference between async vs launch is that async can return a value and launch cannot

On Async statement


runBlocking {
    val job = async {
        println("Running on the background!")
        Thread.sleep(1000)
        "this is done!"
    }

    println("Response is ${job.await()}")
}

This will print “Response is this is done!”

Similar thing on Launch statement


runBlocking {
    val job = launch {
        println("Running on the background!")
        Thread.sleep(1000)
        // "this is done!" -> useless statement :(
    }

    // -- await() doesn't work :(
    // println("Response is ${job.await()}") 
    job.join()
}

How to return a value from launch statement

It is some extra work but can be done, check previous channels post about this:

Returning Values From Launch

Source code: Here


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK