当前位置:嗨网首页>书籍在线阅读

22-协程中的子协程

  
选择背景色: 黄橙 洋红 淡粉 水蓝 草绿 白色 选择字体: 宋体 黑体 微软雅黑 楷体 选择字体大小: 恢复默认

12.5.4 协程中的子协程

当协程的上下文被用来启动另一个协程时,新协程的任务成为父协程任务的子任务。当父协程被取消时,其所有的子协程也会被递归取消。

fun main(args: Array<String>) = runBlocking<Unit> {
    // 开启协程来处理子协程的请求
    val request = launch {
        // job1是独立的上下文
        val job1 = launch {
            println("job1: I have my own context and execute independently!")
            delay(1000)
            //不受父协程影响
            println("job1: I am not affected by cancellation of the request")
        }
        // job2是继承父协程的上下文
        val job2 = launch(coroutineContext) {
            delay(100)
            println("job2: I am a child of the request coroutine")
            delay(1000)
            println("job2: I will not execute this line if my parent request is cancelled")
        }
        job1.join()
        job2.join()
    }
    delay(500)
   //取消请求,所有子协程被取消
    request.cancel()
    delay(1000)
    println("main: Who has survived request cancellation?")
}

运行上面的代码,输出的结果如下。

job1: I have my own context and execute independently!
job2: I am a child of the request coroutine
job1: I am not affected by cancellation of the request
main: Who has survived request cancellation?