I'm trying to make a "MainThreadDispatcher" for in...
# coroutines
e
I'm trying to make a "MainThreadDispatcher" for interop with a java application that has a main thread. The main thread already has an "event loop" and "scheduler" accessible via java with like scheduler.runAfterCycles(3, whatever). But in order to allow for something similar to:
Copy code
runBlocking(MainThreadDispatcher) {
  someLongRunningProcessThatSuspends(...)
}
I need to have an event loop inside of the dispatcher separate to the java one. So I have logic like:
Copy code
override fun dispatch(context: CoroutineContext, block: Runnable) {
  if (eventLoopIsBlocking) {
    eventLoopQueue.push(block)
    eventLoopCondition.signal()
  } else if (isOnMainThread()) block.run()
  else mainThreadScheduler.runOnNextCycle(block)
}
That's fine but what about:
Copy code
override fun scheduleResumeAfterDelay(timeMillis: Long, continuation: CancellableContinuation<Unit>) {
  //here we probably need to know if the event loop would be waiting for this "delay"
  mainThreadScheduler.runAfterCycles(millisToCycles(timeMillis)) { continuation.resume(Unit) }
}
This logic works if you are on another thread and do like:
Copy code
//some other thread/dispatcher
withContext(MainThreadDispatcher) {
  delay(3.seconds) //this will eventually be called, although it may be delayed further by the event loop taking a long time.
  somethingThatNeedsToBeRunFromMainThread()
}
but won't work if you have:
Copy code
//we are on main thread here.
runBlocking(MainThreadDispatcher) {
  delay(3.seconds) //this will never be resumed.
}
So I guess I'm not sure how to make this work cleanly.