CLOVIS
06/23/2026, 7:27 AMsuspend fun runTask() {
val childScope = CoroutineScope(currentCoroutineContext() + Job(currentCoroutineContext().job))
SomeDaemon(childScope).run()
// wait for some condition
childScope.cancel()
}
I think this respects all structured concurrency constraints?Youssef Shoaib [MOD]
06/23/2026, 7:43 AMWout Werkman
06/30/2026, 12:03 PMI think this respects all structured concurrency constraints?Sorry for getting back to this, but this is my passion subject :) Structured Concurrency pretty much means only
coroutineScope. I know it might sound idealistic at first, but trust me, you can do so much more with coroutineScope than you think :)
Constructing a CoroutineScope manually is full of footguns, and should be reserved for complex low level situations.
I'd have to get into details to explain why runTask currently breaks what you should expect of structured concurrency (which I would love to :) ), but the main suggestion is to always try and solve it with coroutineScope first.
In this case, it seems to me that:
suspend fun runTask(): Unit = coroutineScope {
val task = launch { SomeDaemon(this).run() }
// wait for some condition
task.cancel()
}
Would most likely suffice.
I'm sure your actual usecase is more complex, and I would love to look at an example where solving it with coroutineScope seems less feasible. Because I'm giving talks on this topic and would love more feedback :)CLOVIS
06/30/2026, 12:16 PMlaunch -then-cancel works for my use-case. I'm not sure why I didn't think of it 🤔CLOVIS
07/02/2026, 8:28 AMlateinit var but I don't think that's safe.Youssef Shoaib [MOD]
07/02/2026, 8:29 AMlateinit var, but maybe with a CoroutineStart.UNDISPATCHED or whatever it's called (which ensures the coroutine runs immediately)CLOVIS
07/02/2026, 8:30 AMsuspend fun runTask(): Unit = coroutineScope {
val daemon = CompletableDeferredDaemon()
val daemonJob = launch {
SomeDaemon(this)
.also { daemon.complete(it) }
.run()
}
// wait for some condition
… daemon.await().whatever(…) …
daemonJob.cancel()
}CLOVIS
07/02/2026, 8:31 AMUNDISPATCHED in the launch when the daemon gets its context from the launch? The daemon itself shouldn't be UNDISPATCHEDYoussef Shoaib [MOD]
07/02/2026, 8:32 AMCLOVIS
07/02/2026, 8:33 AMCLOVIS
07/02/2026, 8:34 AMWout Werkman
07/02/2026, 9:16 AMSomeDaemon, we're opening another can of worms :)
suspend fun runTask(): Unit = coroutineScope {
val deamonState = MutableStateFlow<SomeDeamonState>(SomeDeamonState.Uninitialized)
val daemonJob = launch {
SomeDaemon(this, deamonState).run() // Now we don't "leak" SomeDeamon from here, but we explicitly share mutable state (also not always optimal ofc)
}
// wait for some condition checking deamonState
daemonJob.cancel()
}CLOVIS
07/02/2026, 9:47 AMSelectorManager from Ktor Sockets, which is a kind of socket factory, so I do need an instance to it directly, but indeed a flow of some more specific value would be a better solution if applicableCLOVIS
07/02/2026, 9:47 AM