什么时候用 Dispatchers.Unconfined
比较合适对比 EmptyCoroutineContext
?
我的用例是我想创建一个 API 来拦截网络调用。我想提供一个可选参数来控制在哪个调度程序上执行拦截。这个参数的默认值应该是Dispatchers.Unconfined
或 EmptyCoroutineContext
?
最佳答案
For the default value of this parameter, should it be Dispatchers.Unconfined or EmptyCoroutineContext?
大多数时候是
Dispatchers.Unconfined
.EmptyCoroutineContext
里面没有元素,语义上它是一个 null object .协程构建器,例如 launch ,指定他们在这种情况下的行为:If the context does not have any dispatcher nor any other ContinuationInterceptor, then Dispatchers.Default is used
.大多数时候你不应该使用 EmptyCoroutineContext
因为您不使用空值或空对象。Dispatchers.Unconfined
不同的是:它立即在当前线程上执行协程,然后在任何名为 resume
的线程中恢复它。 .它通常非常适合拦截常规的非挂起 API 或从阻塞世界回调中调用与协程相关的代码。
关于kotlin-coroutines - 我什么时候应该使用 `Dispatchers.Unconfined` 和 `EmptyCoroutineContext` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55169711/