Hi all, I'm building a multi-platform library tha...
# multiplatform
a
Hi all, I'm building a multi-platform library that's targeting JVM + JS/WASM. I need to also work with
java.util.concurrent.Executor
, which isn't an issue, as I just defined my own for JS. The problem is that I need back-and-forth conversions between my
Executor
and
CoroutineDispatcher
. So on top of the JVM, this isn't an issue:
Copy code
import kotlinx.coroutines.asCoroutineDispatcher
import kotlinx.coroutines.asExecutor

dispatcher.asExecutor()

executor.asCoroutineDispatcher()
But on top of JS, I need to know if these functions are doing the right thing, especially since the JVM implementation seems to be more complicated. So for converting a
CoroutineDispatcher
into an
Executor
, I'm doing this:
Copy code
fun dispatcherAsExecutor(dispatcher: CoroutineDispatcher): Executor =
    object : Executor {
        override fun execute(command: Runnable) {
            dispatcher.dispatch(
                EmptyCoroutineContext,
                command
            )
        }
    }
Or for converting an
Executor
into a
CoroutineDispatcher
:
Copy code
fun executorAsDispatcher(executor: Executor): CoroutineDispatcher =
    object : CoroutineDispatcher() {
        override fun dispatch(context: CoroutineContext, block: Runnable) {
            executor.execute(block)
        }
    }
Where I'm having issues, especially in the latter case, is that I don't know the purpose of the
CoroutineContext
here, especially as it gets ignored — i.e., I hope there isn't some mechanism for it to be passed around that I'm ignoring. IS THIS OK? Thanks.