小编mds*_*ubi的帖子

为什么 kotlin.coroutines.CoroutineContext.Element 继承自 kotlin.coroutines.CoroutineContext

我们可以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}")
}
Run Code Online (Sandbox Code Playgroud)

其中一个值是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.
     */
Run Code Online (Sandbox Code Playgroud)

不太确定是什么An element of the coroutine …

kotlin kotlin-coroutines

3
推荐指数
1
解决办法
680
查看次数

标签 统计

kotlin ×1

kotlin-coroutines ×1