Kotlin Async vs Launch

对着背影说爱祢 提交于 2019-12-22 06:49:41

问题


Kotlin_version = '1.2.41'

I am pretty new to Kotlin. I would like to know what's the difference between async and launch. Especially in the following code

import kotlinx.coroutines.experimental.async
import kotlinx.coroutines.experimental.awaitAll
import kotlinx.coroutines.experimental.delay
import kotlinx.coroutines.experimental.launch
import kotlinx.coroutines.experimental.runBlocking

fun main(args: Array<String>) {
    runBlocking {
        (20..30).forEach {
            launch{
                println("main before" + it)
                val outer = it
                delay(1000L)
                val lists = (1..10)
                        .map { async{anotherMethod(outer, it)}}
                println("main after------------------Awaiting" + it)
                lists.awaitAll()
                println("Done awaiting -main after-----------------" + it)

            }


        }

        println("Hello,") // main thread continues here immediately
    }
}

.

suspend fun anotherMethod (outer: Int,index: Int){
    println("inner-b4----" + outer + "--" + index)
    delay(3000L)
    println("inner-After----" + outer + "--" + index)
}

Vs

fun main(args: Array<String>) {
    runBlocking {
        (20..30).forEach {
            async{
                println("main before" + it)
                val outer = it
                delay(1000L)
                val lists = (1..10)
                        .map { async{anotherMethod(outer, it)}}
                println("main after------------------Awaiting" + it)
                lists.awaitAll()
                println("Done awaiting -main after-----------------" + it)

            }


        }

        println("Hello,") // main thread continues here immediately
    }
}

suspend fun anotherMethod (outer: Int,index: Int){
    println("inner-b4----" + outer + "--" + index)
    delay(3000L)
    println("inner-After----" + outer + "--" + index)
}

回答1:


async does return a Deferred<>, while launch does only return a Job, both start a new coroutine. So it depends if you require a return value or not.

In your first example the launch does not return a value - the last println only produces an Unit. If you use async as in the second example, the overall result will be the same, but you create some useless Deferred<Unit> objects.



来源:https://stackoverflow.com/questions/52820510/kotlin-async-vs-launch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!