CoroutineName 的功能很直白就像名字提到的协程的名称,在使用的时候只需要把它正常的当成一个 CoroutineContext 就行了。
CoroutineName 主要用于测试和调试时更方便的查看代码运行是否符合在我们设计的工作流程上正确执行。
fun main() = runBlocking {val scope = CoroutineScope(EmptyCoroutineContext)val name = CoroutineName("MyCoroutine")scope.launch(name) {println("CoroutineName: ${coroutineContext[CoroutineName]?.name}")}delay(10000)
}输出结果:
CoroutineName: MyCoroutine
如果传给 CoroutineScope,那么这个 CoroutineScope 启动的所有协程都是这个名称:
fun main() = runBlocking {val name = CoroutineName("MyCoroutine")val scope = CoroutineScope(Dispatchers.IO + name)scope.launch {println("CoroutineName: ${coroutineContext[CoroutineName]?.name}")}delay(10000)
}