From 4d55ec6f36a262bda9370897a6224ee9404d3dfc Mon Sep 17 00:00:00 2001 From: InsanusMokrassar Date: Fri, 14 Jun 2024 16:58:40 +0600 Subject: [PATCH] add separated WeakScope --- .../dev/inmo/micro_utils/coroutines/WeakJob.kt | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/WeakJob.kt b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/WeakJob.kt index 0d004efc65a..48a49f295db 100644 --- a/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/WeakJob.kt +++ b/coroutines/src/commonMain/kotlin/dev/inmo/micro_utils/coroutines/WeakJob.kt @@ -4,19 +4,25 @@ import kotlinx.coroutines.* import kotlin.coroutines.CoroutineContext import kotlin.coroutines.EmptyCoroutineContext -private fun CoroutineScope.createWeakSubScope() = CoroutineScope(coroutineContext.minusKey(Job) + Job()).also { newScope -> +fun WeakScope( + context: CoroutineContext +) = CoroutineScope(context.minusKey(Job) + Job()).also { newScope -> newScope.launch { - this@createWeakSubScope.coroutineContext.job.join() + context.job.join() newScope.cancel() } } +fun WeakScope( + scope: CoroutineScope +) = WeakScope(scope.coroutineContext) + fun CoroutineScope.launchWeak( context: CoroutineContext = EmptyCoroutineContext, start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> Unit ): Job { - val scope = createWeakSubScope() + val scope = WeakScope(this) val job = scope.launch(context, start, block) job.invokeOnCompletion { scope.cancel() } return job @@ -27,7 +33,7 @@ fun CoroutineScope.asyncWeak( start: CoroutineStart = CoroutineStart.DEFAULT, block: suspend CoroutineScope.() -> T ): Deferred { - val scope = createWeakSubScope() + val scope = WeakScope(this) val deferred = scope.async(context, start, block) deferred.invokeOnCompletion { scope.cancel() } return deferred