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
Dico
03/15/2019, 5:51 PM
Use
runBlocking
. Wrap the coroutineContext of the coroutine that you started in a
CoroutineScope
.
Dico
03/15/2019, 5:52 PM
Wrap your whole application in the
runBlocking
call.
b
basher
03/15/2019, 5:52 PM
👍
basher
03/15/2019, 5:53 PM
My other thought was to just use a thread-local unconfined coroutine
d
Dico
03/15/2019, 5:57 PM
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
basher
03/15/2019, 6:03 PM
thanks!
d
Dico
03/15/2019, 6:04 PM
Just don't copyright my code so I can keep using it, you're welcome 👍🏻