Kotlin 协程生命周期初探

22 阅读1分钟

Kotlin的协程结构是一种树型结构,coroutineScope{ launch{ } launch{ } } 里面的协程是孩子,外面的协程是父亲,父亲要等子协程做完了事情才能结束。

suspend fun main(){
    coroutineScope {
        launch {
            launch {
                delay(2.seconds)
                println("Child of the enclosing coroutine completed")
            }
            println("Child coroutine 1 completed")
        }
        launch {
            delay(1.seconds)
            println("Child coroutine 2 completed")
        }
    }
    println("Coroutine scope completed")
}

运行结果

Child coroutine 1 completed
Child coroutine 2 completed
Child of the enclosing coroutine completed
Coroutine scope completed