Merge pull request #57 from InsanusMokrassar/0.4.33

0.4.33
This commit is contained in:
InsanusMokrassar 2021-04-05 16:30:58 +06:00 committed by GitHub
commit 126f9d5f41
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 83 additions and 3 deletions

View File

@ -1,5 +1,14 @@
# Changelog
## 0.4.33
* `Versions`:
* `Ktor`: `1.5.2` -> `1.5.3`
* `Coroutines`
* Add `WeakJob` workaround:
* `CoroutineScope#weakLaunch`
* `CoroutineScope#weakAsync`
## 0.4.32
* `Versions`:

View File

@ -0,0 +1,31 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.*
import kotlin.coroutines.CoroutineContext
import kotlin.coroutines.EmptyCoroutineContext
private 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
}

View File

@ -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)
}
}

View File

@ -11,7 +11,7 @@ kotlin_coroutines_version=1.4.3
kotlin_serialisation_core_version=1.1.0
kotlin_exposed_version=0.30.1
ktor_version=1.5.2
ktor_version=1.5.3
klockVersion=2.0.7
@ -44,5 +44,5 @@ dokka_version=1.4.30
# Project data
group=dev.inmo
version=0.4.32
android_code_version=36
version=0.4.33
android_code_version=37