2

我反复发现自己编写代码是这样的:

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

我真正需要的只是协程调度程序,所以我可以编写类似的东西

launch(threadPool) { ... }

或者

withContext(threadPool) { ... }

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

4

1 回答 1

3

目前这不是开箱即用的解决方案,但您可以编写自己的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

于 2018-03-12T08:12:14.473 回答