CLOVIS
10/25/2026, 4:43 PMinterface DaemonScope : CoroutineScope {
// Same signature as 'launch'
suspend fun daemon(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend fun CoroutineScope.() -> Unit,
): Job
}
suspend fun <T> daemonScope(
block: suspend DaemonScope.() -> T,
) = coroutineScope { // Outer scope: all children
val daemonParentJob = Job(this.coroutineContext.job)
coroutineScope { // Inner scope: only non-daemon children
val scope = object : DaemonScope, CoroutineScope by this {
override suspend fun daemon(
context: CoroutineContext,
block: suspend fun CoroutineScope.() -> Unit,
): Job {
return launch(context + daemonParentJob, block)
}
}
block()
// Here, all non-daemon jobs are automatically joined by the scope
}
daemonParentJob.cancel("All non-daemon jobs have terminated, cancelling the daemon jobs")
// Let the scope terminate normally when everything is properly shut down
}Dmitry Khalanskiy [JB]
10/25/2026, 5:12 PMCLOVIS
10/25/2026, 5:15 PM