Kotlin异步与启动 [英] Kotlin Async vs Launch

查看:195
本文介绍了Kotlin异步与启动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Kotlin_version ='1.2.41'

Kotlin_version = '1.2.41'

我对Kotlin很陌生.我想知道asynclaunch有什么区别.特别是在以下代码中

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确实返回Deferred<>,而launch仅返回Job,两者都启动一个新的协程.因此,这取决于您是否需要返回值.

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.

在您的第一个示例中,launch不返回值-最后一个println仅产生一个Unit.如果在第二个示例中使用async,则总体结果将相同,但是创建了一些无用的Deferred<Unit>对象.

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.

这篇关于Kotlin异步与启动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆