CLOVIS
04/02/2026, 8:49 AMfun BackgroundHelperJob(parent: Job): Job {
val job = Job()
parent.invokeOnCompletion {
when (it) {
null -> job.cancel("The parent job has completed, the background helper job should cancel")
is CancellationException -> job.cancel(it)
else -> job.cancel("The parent job has failed, the background helper job should cancel", it)
}
}
return job
}
fun CoroutineScope.launchInBackgroundHelper(
context: CoroutineContext = EmptyCoroutineContext,
block: suspend CoroutineScope.() -> Unit,
): Job {
val parent = this.coroutineContext[Job]
requireNotNull(parent) { "A background helper in a jobless coroutine scope breaks structured concurrency!" }
val helper = BackgroundHelperJob(this.coroutineContext.job)
@Suppress("CoroutineContextWithJob") // the background helper job attaches itself to the parent
return launch(context + helper, block = block)
}
This would be useful for 'side-car'-style services that launch their own coroutines to help the main process progress, but can be trashed without issues. For example, a temporary in-memory cache.Dmitry Khalanskiy [JB]
04/02/2026, 9:08 AMCLOVIS
04/02/2026, 9:39 AM