Is there a way to provide a Dispatcher.Main in nat...
# kotlin-native
b
Is there a way to provide a Dispatcher.Main in native? Comments seem to indicate that on native, we should provide one, but I'm not seeing how to do that (i.e. where we would create and pass it to coroutines)
d
Use
runBlocking
. Wrap the coroutineContext of the coroutine that you started in a
CoroutineScope
.
Wrap your whole application in the
runBlocking
call.
b
👍
My other thought was to just use a thread-local unconfined coroutine
d
Example code for my application which uses an application loop:
Copy code
// Declared here to avoid InvalidMutabilityException in native targets.
private var loopContext: CoroutineContext? = null

object EngineScope : CoroutineScope {
    private fun checkContext() {
        if (loopContext == null) error("Engine context is not present")
    }

    private val nonNullContext: CoroutineContext
        get() {
            checkContext()
            return loopContext!!
        }

    private fun mkContext(base: CoroutineContext) =
        base + SupervisorJob(parent = base[Job]) + CoroutineExceptionHandler { ctx, ex -> printErr("EngineScope Exception Handler", ex) }

    fun runProgram(program: suspend () -> Unit) {
        loopContext?.let { error("Engine context is already present") }

        runBlocking {
            loopContext = mkContext(coroutineContext)
            program()
        }

        loopContext = null
    }

    fun performMainLoop(mainLoop: () -> Unit) {
        checkContext()
        launch {
            while (isActive) {
                yield()
                mainLoop()
            }
        }
    }

    fun stopMainLoop() {
        nonNullContext.cancel()
    }

    override val coroutineContext: CoroutineContext get() = nonNullContext
}
b
thanks!
d
Just don't copyright my code so I can keep using it, you're welcome 👍🏻
😄 1