gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 12:43:27 24 4
gpt4 key购买 nike

什么时候用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com