I have a coroutine dispatcher `d` that I have obta...
# coroutines
u
I have a coroutine dispatcher
d
that I have obtained by calling
.asCoroutineDispatcher()
on a single-threaded executor service. I want to launch long-running coroutines on this dispatcher from synchronous code. The obvious choice seems to be
runBlocking(d) { launch { ... } }
, but that blocks the thread until the job launched by
launch { }
completes. Can I submit a long-running job to
d
from synchronous code without blocking the current thread?
u
You need to create a
val scope : CoroutineScope
Copy code
class XXX {
  val scop = CoroutineScope(SupervisorJob() + d)

  fun launchJob() { 
    scope.launch { ... }
  }

  fun dispose() {
    scope.cancel()
  }
}
The
CoroutineScope
will tell it’s coroutines, which dispatcher to use, how to handle exceptions and most noteably to cancel the potentially whole tree of child coroutines. Disclaimer: Might not even compile.
u
Thank you, I'll try that :)
u
Please read about scopes. I can not say if above setup of the scope is correct for you.
u
Me neither, I'll read up. Thanks for the pointer!
u
oops, i think ther is no SupervisorScope. I’ll change it above
u
Why the SupervisorJob, and why the
d
?
I assume
SubervisorJob
is necessary because
launch
will fail if there is no parent job in the scope?
u
not sure if it will fail. but `scope.cancel()`will actually call
cancel
on scope’s Job which will then cancel all it’s children. So if you do not set a job, cancelation aka structured concurrency will not work.
u
Nevermind, I should just read the docs. Thanks!
Ahh, I see. Thanks!
Thanks, this was exactly what I needed, and it turned out to solve another problem I have had for some time! I can now accomplish what I want without launching any threads at all - I even succeeded with replacing my dispatcher
d
with a custom serial dispatcher that just runs all its jobs on the current thread when a custom
.run()
method is called on it. I am using coroutines to simulate nodes in a network that pass messages back and forth, and this allows me to make the simulation completely deterministic and allows the detection of deadlocks immediately without the use of timeouts.