关闭ExecutorCoroutineDispatcher的底层Executor

时间:2018-03-11 07:25:14

标签: kotlin kotlinx.coroutines

我反复发现自己编写代码:

val threadPoolExecutor = Executors.newCachedThreadPool()
val threadPool = threadPool.asCoroutineDispatcher()

我真正需要的只是协程调度员,所以我可以编写像

这样的东西
launch(threadPool) { ... }

withContext(threadPool) { ... }

我需要threadPoolExecutor只是为了能够在清理时关闭它。有没有办法使用coroutine调度程序实例来关闭它?

1 个答案:

答案 0 :(得分:2)

目前这不是开箱即用的解决方案,但您可以编写自己的asCoroutineDispatcher扩展程序来提供此类体验:

abstract class CloseableCoroutineDispatcher : CoroutineDispatcher(), Closeable

fun ExecutorService.asCoroutineDispatcher(): CloseableCoroutineDispatcher =
    object : CloseableCoroutineDispatcher() {
        val delegate = (this@asCoroutineDispatcher as Executor).asCoroutineDispatcher()
        override fun isDispatchNeeded(context: CoroutineContext): Boolean = delegate.isDispatchNeeded(context)
        override fun dispatch(context: CoroutineContext, block: Runnable) = delegate.dispatch(context, block)
        override fun close() = shutdown()
    }

此问题导致以下更改请求:https://github.com/Kotlin/kotlinx.coroutines/issues/278