Merge pull request #39 from InsanusMokrassar/0.4.18

0.4.18
This commit is contained in:
InsanusMokrassar 2021-01-17 17:17:39 +06:00 committed by GitHub
commit 79ef03ed0c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 77 additions and 2 deletions

View File

@ -1,5 +1,13 @@
# Changelog
## 0.4.18
* `Coroutines`:
* New extension `Iterable<Deferred>#awaitFirst` has been added
* `Serialization`
* `Base 64`
* New `Base64ByteArraySerializer` has been added
## 0.4.17
* `Common`

View File

@ -0,0 +1,32 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.*
import kotlin.coroutines.*
suspend fun <T> Iterable<Deferred<T>>.awaitFirst(
scope: CoroutineScope,
cancelOnResult: Boolean = true
): T = suspendCoroutine<T> { continuation ->
scope.launch(SupervisorJob()) {
val scope = this
forEach {
scope.launch {
continuation.resume(it.await())
scope.cancel()
}
}
}
}.also {
if (cancelOnResult) {
forEach {
try {
it.cancel()
} catch (e: IllegalStateException) {
e.printStackTrace()
}
}
}
}
suspend fun <T> Iterable<Deferred<T>>.awaitFirst(
cancelOthers: Boolean = true
): T = awaitFirst(CoroutineScope(coroutineContext), cancelOthers)

View File

@ -0,0 +1,34 @@
package dev.inmo.micro_utils.coroutines
import kotlinx.coroutines.*
import org.junit.Test
import kotlin.test.assertEquals
import kotlin.test.assertTrue
class AwaitFirstTests {
private fun CoroutineScope.createTestDeferred(value: Int, wait: Long = 100000) = async(start = CoroutineStart.LAZY) { delay(wait); value }
@Test
fun testThatAwaitFirstIsWorkingCorrectly() {
val baseScope = CoroutineScope(Dispatchers.Default)
val resultDeferred = baseScope.createTestDeferred(-1, 0)
val deferreds = listOf(
baseScope.async { createTestDeferred(0) },
baseScope.async { createTestDeferred(1) },
baseScope.async { createTestDeferred(2) },
resultDeferred
)
val controlJob = baseScope.launch {
delay(1000000)
}
val result = baseScope.launchSynchronously {
val result = deferreds.awaitFirst(baseScope)
assertTrue(baseScope.isActive)
assertTrue(controlJob.isActive)
result
}
assertEquals(baseScope.launchSynchronously { resultDeferred.await() }, result)
assertTrue(deferreds.all { it == resultDeferred || it.isCancelled })
}
}

View File

@ -40,5 +40,5 @@ dokka_version=1.4.20
# Project data
group=dev.inmo
version=0.4.17
android_code_version=21
version=0.4.18
android_code_version=22

View File

@ -18,3 +18,4 @@ open class Base64Serializer<T>(
}
object Base64StringSerializer : Base64Serializer<String>({ it }, { it })
object Base64ByteArraySerializer : Base64Serializer<ByteArray>({ it.decodeToString() }, { it.encodeToByteArray() })