However, this parent-child relation can be explicitly overriden in one of two ways:
When a different scope is explicitly specified when launching a coroutine (for example, GlobalScope.launch), then it does not inherit a Job from the parent scope.
When a different Job object is passed as the context for the new coroutine (as shown in the example below), then it overrides the Job of the parent scope.
In both cases, the launched coroutine is not tied to the scope it was launched from and operates independently.
funmain() = runBlocking<Unit> { // 启动一个协程来处理某种传入请求(request) val request = launch { // 一个TopLevelScope CoroutineScope(context = Dispatchers.Default).launch { println("NewTopLevelScope job1: I run in my own Job and execute independently!") delay(1000) println("NewTopLevelScope job1: I am not affected by cancellation of the request") } // 另一个则承袭了父协程的上下文 launch { delay(100) println("ChildCoroutine job2: I am a child of the request coroutine") delay(1000) println("ChildCoroutine job2: I will not execute this line if my parent request is cancelled") } } delay(500) request.cancel() // 取消请求(request)的执行 println("main: Who has survived request cancellation?") delay(1000) // 主线程延迟一秒钟来看看发生了什么 }
结果 NewTopLevelScope job1: I run in my own Job and execute independently! ChildCoroutine job2: I am a child of the request coroutine main: Who has survived request cancellation? NewTopLevelScope job1: I am not affected by cancellation of the request
funmain() = runBlocking<Unit> { // 启动一个协程来处理某种传入请求(request) val request = launch { // 生成了两个子作业 launch(Job()) { println("job1: I run in my own Job and execute independently!") delay(1000) println("job1: I am not affected by cancellation of the request") } // 另一个则承袭了父协程的上下文 launch { 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") } } delay(500) request.cancel() // 取消请求(request)的执行 println("main: Who has survived request cancellation?") delay(1000) // 主线程延迟一秒钟来看看发生了什么 }
结果 job1: I run in my own Job and execute independently! job2: I am a child of the request coroutine main: Who has survived request cancellation? job1: I am not affected by cancellation of the request