Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 ?

like image 686
Dmitriy Puchkov Avatar asked Nov 22 '25 14:11

Dmitriy Puchkov


1 Answers

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

suspend fun fetchMedia(): Flow<MediaItem> {
    return withContext(myThreadPool.asCoroutineDispatcher()) {...} 
}
like image 90
Glenn Sandoval Avatar answered Nov 25 '25 04:11

Glenn Sandoval