What about adding daemon scopes? Daemon scopes fi...
# coroutines
c
What about adding daemon scopes? Daemon scopes fill a missing piece in structured concurrency: • Structured concurrency says that a scope must not terminate while it has an unterminated children • A normal scope waits for its children • A daemon scope can launch daemons, which are cancelled at the end of the scope instead of being joined Proposed API:
Copy code
interface 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
}
d
c
Thanks, I've added this as a comment