Skip to content

Commit

Permalink
Issue #1317: Kotlin - Add typed variants of Uni.awaitSuspending
Browse files Browse the repository at this point in the history
  • Loading branch information
heubeck committed Jul 24, 2023
1 parent 56848d6 commit b9905f1
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
11 changes: 11 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,12 +38,23 @@ 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].
*
* If the surrounding coroutine fails or gets cancelled that failure is propagated as well.
*/
@ExperimentalCoroutinesApi

fun <T> Deferred<T>.asUni(): Uni<T> = Uni.createFrom().emitter { em: UniEmitter<in T> ->
invokeOnCompletion {
try {
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()
}
}

0 comments on commit b9905f1

Please sign in to comment.