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