简体   繁体   English

如何创建在我的 ThreadPoolExecutor 上工作的自定义 Kotlin 协程调度程序?

[英]How to create custom Kotlin coroutine dispatcher worked on my ThreadPoolExecutor?

In the process of migration to Kotlin, the question arose.在迁移到 Kotlin 的过程中,问题出现了。
We already have some ThreadPools for different reasons.由于不同的原因,我们已经有了一些线程池。
How to execute coroutine on existed ThreadPool?如何在现有的 ThreadPool 上执行协程?

For exampe this code :例如这个代码:

    suspend fun fetchMedia(): Flow<MediaItem> {
        return withContext(Dispatchers.IO) {...} 
    }

How to replace Dispatchers.IO to my own ThreadPoolExecutor ?如何将 Dispatchers.IO 替换为我自己的 ThreadPoolExecutor ?

You can use Executor ThreadPools calling asCoroutineDispatcher() on it, like this:您可以使用 Executor ThreadPools 在其上调用asCoroutineDispatcher() ,如下所示:

suspend fun fetchMedia(): Flow<MediaItem> {
    return withContext(myThreadPool.asCoroutineDispatcher()) {...} 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM