kotlin-coroutines - 我什么时候应该使用 `Dispatchers.Unconfined` 和 `EmptyCoroutineContext` ?

标签 kotlin-coroutines

什么时候用 Dispatchers.Unconfined 比较合适对比 EmptyCoroutineContext ?

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

最佳答案

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/

相关文章:

kotlin - 如何在返回 Deferred<T> 的异步函数中进行延迟

kotlin - 如何理解协程取消是合作的

android - 使用 launch() 范围时无法为 LiveData 变量赋值,但可以使用 runBlocking() 为 LiveData 赋值

android - Coroutines Channel values consumeEach waits 而不是一次消费

go - 哪个协程(goroutines 和 kotlin coroutines)更快?

android - 使用协程进行多次循环调用

Android Livedata Observer 协程 Kotlin

android - 向 Gson 注册此类型的 InstanceCreator 可能会解决此问题

android - 如何从使用 .await() 调用的方法返回异常

spring - 如何将 kotlin 协程与响应式 Spring 数据一起使用