Folks I know how to convert `ExecutorService` to a...
# coroutines
v
Folks I know how to convert
ExecutorService
to a coroutine dispatcher. How can I do it the other way around i.e. get ExecutorService from disptacher
s
I don't think that's possible, because a Dispatcher is not necessarily backed by am ExecutorService.
v
So there is no way for me to get the
ExecutorService
of
<http://Dispatchers.IO|Dispatchers.IO>
for example?
s
They may not be using any ExecutorService....
Maybe you could do some inspection/reflection of the classes, looking at private fields and methods, bit that would be error prone and not stable
v
I would rather stay away from that 🙂 but thanks though 😄
b
I use the following for Executor, it wouldn’t be that bad to wire up the methods to make it work as an ExecutorService
Copy code
fun CoroutineDispatcher.asExecutor(): Executor = CoroutineScopeExecutor(this)

private class CoroutineScopeExecutor(private val dispatcher: CoroutineDispatcher) : CoroutineScope, Executor {
    private val job = SupervisorJob()
    override val coroutineContext get() = dispatcher + job
    override fun execute(command: Runnable) {
        if (!job.isActive) {
            throw RejectedExecutionException("Job has been closed")
        }

        launch {
            command.run()
        }
    } 
}