mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-29 21:48:45 +00:00
add separated WeakScope
This commit is contained in:
parent
f373524f34
commit
4d55ec6f36
@ -4,19 +4,25 @@ import kotlinx.coroutines.*
|
|||||||
import kotlin.coroutines.CoroutineContext
|
import kotlin.coroutines.CoroutineContext
|
||||||
import kotlin.coroutines.EmptyCoroutineContext
|
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 {
|
newScope.launch {
|
||||||
this@createWeakSubScope.coroutineContext.job.join()
|
context.job.join()
|
||||||
newScope.cancel()
|
newScope.cancel()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun WeakScope(
|
||||||
|
scope: CoroutineScope
|
||||||
|
) = WeakScope(scope.coroutineContext)
|
||||||
|
|
||||||
fun CoroutineScope.launchWeak(
|
fun CoroutineScope.launchWeak(
|
||||||
context: CoroutineContext = EmptyCoroutineContext,
|
context: CoroutineContext = EmptyCoroutineContext,
|
||||||
start: CoroutineStart = CoroutineStart.DEFAULT,
|
start: CoroutineStart = CoroutineStart.DEFAULT,
|
||||||
block: suspend CoroutineScope.() -> Unit
|
block: suspend CoroutineScope.() -> Unit
|
||||||
): Job {
|
): Job {
|
||||||
val scope = createWeakSubScope()
|
val scope = WeakScope(this)
|
||||||
val job = scope.launch(context, start, block)
|
val job = scope.launch(context, start, block)
|
||||||
job.invokeOnCompletion { scope.cancel() }
|
job.invokeOnCompletion { scope.cancel() }
|
||||||
return job
|
return job
|
||||||
@ -27,7 +33,7 @@ fun <T> CoroutineScope.asyncWeak(
|
|||||||
start: CoroutineStart = CoroutineStart.DEFAULT,
|
start: CoroutineStart = CoroutineStart.DEFAULT,
|
||||||
block: suspend CoroutineScope.() -> T
|
block: suspend CoroutineScope.() -> T
|
||||||
): Deferred<T> {
|
): Deferred<T> {
|
||||||
val scope = createWeakSubScope()
|
val scope = WeakScope(this)
|
||||||
val deferred = scope.async(context, start, block)
|
val deferred = scope.async(context, start, block)
|
||||||
deferred.invokeOnCompletion { scope.cancel() }
|
deferred.invokeOnCompletion { scope.cancel() }
|
||||||
return deferred
|
return deferred
|
||||||
|
Loading…
Reference in New Issue
Block a user