mirror of
https://github.com/InsanusMokrassar/MicroUtils.git
synced 2024-11-17 13:53:49 +00:00
weak jobs workaround
This commit is contained in:
parent
550fc59d9d
commit
36deab4909
@ -2,6 +2,10 @@
|
||||
|
||||
## 0.4.33
|
||||
|
||||
* `Coroutines`
|
||||
* Add `WeakJob` workaround:
|
||||
* `CoroutineScope#`
|
||||
|
||||
## 0.4.32
|
||||
|
||||
* `Versions`:
|
||||
|
@ -0,0 +1,31 @@
|
||||
package dev.inmo.micro_utils.coroutines
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import kotlin.coroutines.CoroutineContext
|
||||
import kotlin.coroutines.EmptyCoroutineContext
|
||||
|
||||
fun CoroutineScope.createWeakSubScope() = CoroutineScope(coroutineContext.minusKey(Job)).also { newScope ->
|
||||
coroutineContext.job.invokeOnCompletion { newScope.cancel() }
|
||||
}
|
||||
|
||||
fun CoroutineScope.weakLaunch(
|
||||
context: CoroutineContext = EmptyCoroutineContext,
|
||||
start: CoroutineStart = CoroutineStart.DEFAULT,
|
||||
block: suspend CoroutineScope.() -> Unit
|
||||
): Job {
|
||||
val scope = createWeakSubScope()
|
||||
val job = scope.launch(context, start, block)
|
||||
job.invokeOnCompletion { scope.cancel() }
|
||||
return job
|
||||
}
|
||||
|
||||
fun <T> CoroutineScope.weakAsync(
|
||||
context: CoroutineContext = EmptyCoroutineContext,
|
||||
start: CoroutineStart = CoroutineStart.DEFAULT,
|
||||
block: suspend CoroutineScope.() -> T
|
||||
): Deferred<T> {
|
||||
val scope = createWeakSubScope()
|
||||
val deferred = scope.async(context, start, block)
|
||||
deferred.invokeOnCompletion { scope.cancel() }
|
||||
return deferred
|
||||
}
|
@ -0,0 +1,40 @@
|
||||
package dev.inmo.micro_utils.coroutines
|
||||
|
||||
import kotlinx.coroutines.*
|
||||
import org.junit.Test
|
||||
|
||||
class WeakJob {
|
||||
@Test
|
||||
fun `test that weak jobs works correctly`() {
|
||||
val scope = CoroutineScope(Dispatchers.Default)
|
||||
lateinit var weakLaunchJob: Job
|
||||
lateinit var weakAsyncJob: Job
|
||||
scope.launchSynchronously {
|
||||
val completeDeferred = Job()
|
||||
coroutineScope {
|
||||
weakLaunchJob = weakLaunch {
|
||||
while (isActive) {
|
||||
delay(100L)
|
||||
}
|
||||
}
|
||||
weakAsyncJob = weakAsync {
|
||||
while (isActive) {
|
||||
delay(100L)
|
||||
}
|
||||
}
|
||||
|
||||
coroutineContext.job.invokeOnCompletion {
|
||||
scope.launch {
|
||||
delay(1000L)
|
||||
completeDeferred.complete()
|
||||
}
|
||||
}
|
||||
launch { delay(1000L); cancel() }
|
||||
}
|
||||
completeDeferred.join()
|
||||
}
|
||||
|
||||
assert(!weakLaunchJob.isActive)
|
||||
assert(!weakAsyncJob.isActive)
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user