Skip to content

Commit

Permalink
Ensure takeItem can return null values
Browse files Browse the repository at this point in the history
  • Loading branch information
JakeWharton committed Nov 3, 2022
1 parent ff1959f commit f91b176
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/commonMain/kotlin/app/cash/turbine/channel.kt
Original file line number Diff line number Diff line change
Expand Up @@ -156,8 +156,10 @@ internal fun <T> ReceiveChannel<T>.takeEventUnsafe(): Event<T>? {
* @throws AssertionError if the next event was completion or an error, or no event.
*/
public fun <T> ReceiveChannel<T>.takeItem(name: String? = null): T {
val event = takeEvent()
return (event as? Event.Item)?.value ?: unexpectedEvent(name, event, "item")
return when (val event = takeEvent()) {
is Event.Item -> event.value
else -> unexpectedEvent(name, event, "item")
}
}

/**
Expand Down
9 changes: 7 additions & 2 deletions src/commonTest/kotlin/app/cash/turbine/TurbineTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ package app.cash.turbine
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFailsWith
import kotlin.test.assertNull
import kotlin.test.assertSame
import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.CoroutineScope
Expand Down Expand Up @@ -160,9 +161,11 @@ class TurbineTest {
@Test
fun awaitItem() = runTest {
val item = Any()
val channel = Turbine<Any>()
val channel = Turbine<Any?>()
channel.add(item)
channel.add(null)
assertSame(item, channel.awaitItem())
assertNull(channel.awaitItem())
}

@Test
Expand Down Expand Up @@ -245,9 +248,11 @@ class TurbineTest {
@Test
fun takeItem() = withTestScope {
val item = Any()
val channel = Turbine<Any>()
val channel = Turbine<Any?>()
channel.add(item)
channel.add(null)
assertSame(item, channel.takeItem())
assertNull(channel.takeItem())
}

@Test
Expand Down

0 comments on commit f91b176

Please sign in to comment.