我们可以提供一个可选的CoroutineContext
,同时从像launch
这样的构建器函数创建协同程序。
launch(Dispatchers.Unconfined) { // not confined -- will work with main thread
println("Unconfined : I'm working in thread ${Thread.currentThread().name}")
delay(500)
println("Unconfined : After delay in thread ${Thread.currentThread().name}")
}
其中一个值是Dispatchers.Unconfined
。我认为Dispatchers.Unconfined
将继承CoroutineContext
,确实如此。但是以一种非常复杂的方式对我来说并不是很清楚。添加了类层次结构的屏幕截图。
它继承自CoroutineContext.Element
。这是CoroutineContext
内部的嵌套接口。这个嵌套的接口继承了外部/父接口,CoroutineContext
的所有有用实现都实现了这个嵌套接口。
我不确定为什么使用这种机制或其他地方使用或可以使用这种模式。嵌套接口AFAIK唯一用于创建新命名空间的地方,如Map.Entry
。官方文件也很少说,
/**
* An element of the [CoroutineContext]. An element of the coroutine context is a singleton context by itself.
*/
不确定An element of the coroutine context is a singleton context by itself.
是什么意思。
我知道这是一个好奇的问题。因此不需要及时的响应。但任何帮助将不胜感激。
协程上下文是一组元素。协程上下文的一个元素本身就是一个单例上下文。这意味着当作为集合(作为协程上下文)查看时,元素表示单元素集(也称为单例)。