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

5.7k views Asked by At

In the process of migration to Kotlin, the question arose.
We already have some ThreadPools for different reasons.
How to execute coroutine on existed ThreadPool?

For exampe this code :

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

How to replace Dispatchers.IO to my own ThreadPoolExecutor ?

1

There are 1 answers

3
Glenn Sandoval On BEST ANSWER

You can use Executor ThreadPools calling asCoroutineDispatcher() on it, like this:

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