Skip to content

Commit

Permalink
Add withLifetime
Browse files Browse the repository at this point in the history
  • Loading branch information
Iliya-usov committed Aug 18, 2023
1 parent 9231ad6 commit 7f06ce2
Showing 1 changed file with 20 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,24 @@ suspend fun <T> lifetimedCoroutineScope(lifetime: Lifetime, action: suspend Coro
lifetime.createNested().synchronizeWith(coroutineContext[Job]!!)

action()
}


/**
* The same as withContext, but creates a [Lifetime] that will be terminated only after the passed [action] and its [CoroutineScope] are completed
*
* @throws IllegalArgumentException If the given [context] contains a [Job].
**/
private suspend fun withLifetime(context: CoroutineContext = EmptyCoroutineContext, action: suspend CoroutineScope.(Lifetime) -> Unit) {
require(context[Job] == null) {
"Context must not specify a Job: $context"
}

withContext(context) {
Lifetime.using { lifetime ->
coroutineScope {
action(lifetime)
}
}
}
}

0 comments on commit 7f06ce2

Please sign in to comment.