https://kotlinlang.org logo
#coroutines
Title
# coroutines
e

Exerosis

07/02/2022, 11:24 AM
I've got a framework with a scheduler somewhat like this one: https://srcb.in/Re5YK27o2Z And I'm trying to make a dispatcher that works with this, so with the above dispatcher I could do:
Copy code
class MyWrapper(init: suspend () -> (Unit)) : ExampleFrameworkApp {
  override fun onInit() = blocking { init() }
}
As well as other framework calls (like events off the event bus etc.) I would like to be able to say something like:
Copy code
class MyApplication : MyWrapper({
  withContext(IO) {
    http.get("..")
  }
  delay(1.second)
  .. etc.
})
However the issue is that when withContext resumes it will call dispatch from an IO thread that schedules the resume, however, we are currently blocking the main thread so that never happens and we deadlock. I think I need a local event loop or something along those lines, is there a builtin construct I could use or do I need to make my own system here?
n

Nick Allen

07/05/2022, 4:52 PM
so with the above dispatcher I could do
Avoid any solution that involves blocking on the main thread. Launch your coroutines instead.
withContext(IO) {
Moving off the main thread only helps when you are not already blocking it. This is why you need to launch from the main thread callbacks.
I think I need a local event loop or something along those lines, is there a builtin construct
Yes, if your dispatcher returns false for
isDispatchNeeded
, then a shared thread local loop is used. That won't fix your dead-lock, though. You can look at existing integrations for inspiration for wrapping your scheduler: https://github.com/Kotlin/kotlinx.coroutines/blob/master/ui/kotlinx-coroutines-swing/src/SwingDispatcher.kt There's ones for swing, javafx, and android.
26 Views