我应何时使用`Dispatchers.Unconfined`和`EmptyCoroutineContext`?

时间:2019-03-14 18:30:14

标签: kotlin-coroutines

何时使用Dispatchers.UnconfinedEmptyCoroutineContext

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

1 个答案:

答案 0 :(得分:1)

  

该参数的默认值是Dispatchers.Unconfined还是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,因为您不使用null或null对象。

Dispatchers.Unconfined有所不同:它在当前线程上立即执行协程,随后在称为resume的任何线程中恢复协程。 通常,它很适合诸如拦截常规非暂停API或从协程相关代码阻止世界回调的事情。