From 0738d1b55b2e47500af249be111b9816c239b254 Mon Sep 17 00:00:00 2001 From: Florian Heubeck Date: Mon, 24 Jul 2023 21:41:02 +0200 Subject: [PATCH] Issue #1317: Kotlin - Add typed variants of Uni.awaitSuspending --- .../io/smallrye/mutiny/coroutines/Uni.kt | 10 ++++ .../coroutines/UniAwaitSuspendingTest.kt | 48 +++++++++++++++++++ 2 files changed, 58 insertions(+) diff --git a/kotlin/src/main/kotlin/io/smallrye/mutiny/coroutines/Uni.kt b/kotlin/src/main/kotlin/io/smallrye/mutiny/coroutines/Uni.kt index 21fee41f6..c5bff1ded 100644 --- a/kotlin/src/main/kotlin/io/smallrye/mutiny/coroutines/Uni.kt +++ b/kotlin/src/main/kotlin/io/smallrye/mutiny/coroutines/Uni.kt @@ -38,6 +38,16 @@ suspend fun Uni.awaitSuspending() = suspendCancellableCoroutine { cont } } +/** + * Like [awaitSuspending], but fails with an [IllegalStateException] if there's no item produced by this [Uni]. + */ +suspend fun Uni.awaitItem(): T = checkNotNull(awaitSuspending()) { "Uni did not emit an item" } + +/** + * Like [awaitSuspending], but with the explicit need of `null` handling. + */ +suspend fun Uni.awaitItemOrNull(): T? = awaitSuspending() + /** * Provide this [Deferred]s value or failure as [Uni]. * diff --git a/kotlin/src/test/kotlin/io/smallrye/mutiny/coroutines/UniAwaitSuspendingTest.kt b/kotlin/src/test/kotlin/io/smallrye/mutiny/coroutines/UniAwaitSuspendingTest.kt index 8acfe4489..c8912919d 100644 --- a/kotlin/src/test/kotlin/io/smallrye/mutiny/coroutines/UniAwaitSuspendingTest.kt +++ b/kotlin/src/test/kotlin/io/smallrye/mutiny/coroutines/UniAwaitSuspendingTest.kt @@ -18,6 +18,7 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeout import org.assertj.core.api.Assertions.assertThat +import org.assertj.core.api.Assertions.assertThatThrownBy class UniAwaitSuspendingTest { @@ -141,4 +142,51 @@ class UniAwaitSuspendingTest { // Then assertThat(item).isEqualTo(23) } + + @Test + fun `test awaitItem with non null item`() { + // Given + val nonNullUni: Uni = Uni.createFrom().item("blue pill") + + // When + val nonNullItem: String = testBlocking { nonNullUni.awaitItem() } + + // Then + assertThat(nonNullItem).isNotNull() + } + + @Test + fun `test awaitItem with null item`() { + // Given + val nullUni: Uni = Uni.createFrom().nullItem(); + + // When & Then + assertThatThrownBy { + testBlocking { nullUni.awaitItem() } + }.isInstanceOf(IllegalStateException::class.java).hasMessage("Uni did not emit an item") + } + + @Test + fun `test awaitItemOrNull with non null item`() { + // Given + val nonNullUni: Uni = Uni.createFrom().item("blue pill") + + // When + val nonNullItem: String? = testBlocking { nonNullUni.awaitItemOrNull() } + + // Then + assertThat(nonNullItem).isNotNull() + } + + @Test + fun `test awaitItemOrNull with null item`() { + // Given + val nullUni: Uni = Uni.createFrom().nullItem() + + // When + val nullItem: String? = testBlocking { nullUni.awaitItemOrNull() } + + // Then + assertThat(nullItem).isNull() + } }