首页 > 解决方案 > 在 withContext 之后切换协程上下文

问题描述

假设我们有io用于阻塞操作的协程上下文和async用于非阻塞操作(如协程执行)的协程上下文。如何有效地实施追随?

/**
 * Eval [f] on thread pool defined by [on], then continue execution on [continueOn] context
 */
suspend fun <A> eval<A>(f: () -> A, on: CoroutineContext, continueOn: CoroutineContext): A

eval({ readFileBlocking() }, io, async)

eval可以从任何上下文中调用,包括Unconfined. withContext(continueOn) { withContext(on) { f() }}有效但效率低下 - 它强制最多 4 个线程池切换,而最佳值为 2(从输入上下文到阻塞池,然后到结果上下文)

问答

标签: kotlinkotlin-coroutines

解决方案


推荐阅读