basher
03/15/2019, 5:50 PMDico
03/15/2019, 5:51 PMrunBlocking
. Wrap the coroutineContext of the coroutine that you started in a CoroutineScope
.Dico
03/15/2019, 5:52 PMrunBlocking
call.basher
03/15/2019, 5:52 PMbasher
03/15/2019, 5:53 PMDico
03/15/2019, 5:57 PM// 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
}
basher
03/15/2019, 6:03 PMDico
03/15/2019, 6:04 PM