Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue #1317: Kotlin - Add typed variants of Uni.awaitSuspending #1322

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions kotlin/src/main/kotlin/io/smallrye/mutiny/coroutines/Uni.kt
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,16 @@ suspend fun <T> Uni<T>.awaitSuspending() = suspendCancellableCoroutine<T> { cont
}
}

/**
* Like [awaitSuspending], but fails with an [IllegalStateException] if there's no item produced by this [Uni].
*/
suspend fun <T> Uni<T>.awaitItem(): T = checkNotNull(awaitSuspending()) { "Uni did not emit an item" }

/**
* Like [awaitSuspending], but with the explicit need of `null` handling.
*/
suspend fun <T> Uni<T>.awaitItemOrNull(): T? = awaitSuspending()

/**
* Provide this [Deferred]s value or failure as [Uni].
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 {

Expand Down Expand Up @@ -141,4 +142,51 @@ class UniAwaitSuspendingTest {
// Then
assertThat(item).isEqualTo(23)
}

@Test
fun `test awaitItem with non null item`() {
// Given
val nonNullUni: Uni<String> = 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<String> = 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<String> = 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<String> = Uni.createFrom().nullItem()

// When
val nullItem: String? = testBlocking { nullUni.awaitItemOrNull() }

// Then
assertThat(nullItem).isNull()
}
}