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

Dmitriy Puchkov :

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 ?

Glenn Sandoval :

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

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=237584&siteId=1