什么时候应该使用 `Dispatchers.Unconfined` 与 `EmptyCoroutineContext`?

When should I use `Dispatchers.Unconfined` vs `EmptyCoroutineContext`?

什么时候使用 Dispatchers.UnconfinedEmptyCoroutineContext 比较合适?

我的用例是我想创建一个 API 来拦截网络调用。我想提供一个可选参数来控制在哪个调度程序上执行拦截。这个参数的默认值,应该是Dispatchers.Unconfined还是EmptyCoroutineContext

For the default value of this parameter, should it be Dispatchers.Unconfined or EmptyCoroutineContext?

大部分时间是 Dispatchers.Unconfined

EmptyCoroutineContext 中没有元素,在语义上它是一个 null object. Coroutine builders, such as launch,指定它们在这种情况下的行为:If the context does not have any dispatcher nor any other ContinuationInterceptor, then Dispatchers.Default is used。大多数时候你不应该使用 EmptyCoroutineContext 因为你不使用 null 或 null 对象。

Dispatchers.Unconfined 不同:它立即在当前线程上执行协程,然后在调用 resume 的任何线程中恢复它。 它通常非常适合拦截常规非挂起 API 或从阻塞世界回调中调用与协程相关的代码。