Skip to content

Pr/2230 #2287

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

Merged
merged 5 commits into from
Oct 8, 2020
Merged

Pr/2230 #2287

Show file tree
Hide file tree
Changes from 4 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
39 changes: 25 additions & 14 deletions kotlinx-coroutines-core/common/src/flow/terminal/Reduce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
package kotlinx.coroutines.flow

import kotlinx.coroutines.flow.internal.*
import kotlinx.coroutines.internal.Symbol
import kotlin.jvm.*

/**
Expand Down Expand Up @@ -47,33 +48,43 @@ public suspend inline fun <T, R> Flow<T>.fold(
}

/**
* The terminal operator, that awaits for one and only one value to be published.
* The terminal operator that awaits for one and only one value to be emitted.
* Throws [NoSuchElementException] for empty flow and [IllegalStateException] for flow
* that contains more than one element.
*/
public suspend fun <T> Flow<T>.single(): T {
var result: Any? = NULL
collect { value ->
if (result !== NULL) error("Expected only one element")
require(result == NULL) { "Flow has more than one element" }
result = value
}

if (result === NULL) throw NoSuchElementException("Expected at least one element")
@Suppress("UNCHECKED_CAST")
if (result === NULL) throw NoSuchElementException("Flow is empty")
return result as T
}

/**
* The terminal operator, that awaits for one and only one value to be published.
* Throws [IllegalStateException] for flow that contains more than one element.
* The terminal operator that awaits for one and only one value to be emitted.
* Returns the single value or `null`, if the flow was empty or emitted more than one value.
*/
public suspend fun <T: Any> Flow<T>.singleOrNull(): T? {
var result: T? = null
public suspend fun <T> Flow<T>.singleOrNull(): T? {
var result: Any? = NULL
collect { value ->
if (result != null) error("Expected only one element")
result = value
/*
* result === NULL -> first value
* result === user value -> we already had first value and second one arrived
* result === DONE -> we've seen more than one value, time to return it
* as well.
*/
result = if (result === NULL) {
value
} else {
// Indicator that more than one value was observed
DONE
}
}
return result
// Symbols are never leaked, so it's one comparison versus two
return if (result is Symbol) null else result as T
}

/**
Expand Down Expand Up @@ -112,7 +123,7 @@ public suspend fun <T> Flow<T>.first(predicate: suspend (T) -> Boolean): T {
* The terminal operator that returns the first element emitted by the flow and then cancels flow's collection.
* Returns `null` if the flow was empty.
*/
public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
public suspend fun <T> Flow<T>.firstOrNull(): T? {
var result: T? = null
collectWhile {
result = it
Expand All @@ -122,10 +133,10 @@ public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
}

/**
* The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
* The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
* Returns `null` if the flow did not contain an element matching the [predicate].
*/
public suspend fun <T : Any> Flow<T>.firstOrNull(predicate: suspend (T) -> Boolean): T? {
public suspend fun <T> Flow<T>.firstOrNull(predicate: suspend (T) -> Boolean): T? {
var result: T? = null
collectWhile {
if (predicate(it)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ class OnCompletionTest : TestBase() {

@Test
fun testSingle() = runTest {
assertFailsWith<IllegalStateException> {
assertFailsWith<IllegalArgumentException> {
flowOf(239).onCompletion {
assertNull(it)
expect(1)
Expand All @@ -240,7 +240,7 @@ class OnCompletionTest : TestBase() {
expectUnreached()
} catch (e: Throwable) {
// Second emit -- failure
assertTrue { e is IllegalStateException }
assertTrue { e is IllegalArgumentException }
throw e
}
}.single()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,12 @@ class FirstTest : TestBase() {
assertNull(emptyFlow<Int>().firstOrNull { true })
}

@Test
fun testFirstOrNullWithNullElement() = runTest {
assertNull(flowOf<String?>(null).firstOrNull())
assertNull(flowOf<String?>(null).firstOrNull { true })
}

@Test
fun testFirstOrNullWhenErrorCancelsUpstream() = runTest {
val latch = Channel<Unit>()
Expand Down
10 changes: 7 additions & 3 deletions kotlinx-coroutines-core/common/test/flow/terminal/SingleTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ package kotlinx.coroutines.flow
import kotlinx.coroutines.*
import kotlin.test.*

class SingleTest : TestBase() {
class SingleTest : TestBase() {

@Test
fun testSingle() = runTest {
Expand All @@ -25,8 +25,8 @@ class SingleTest : TestBase() {
emit(239L)
emit(240L)
}
assertFailsWith<RuntimeException> { flow.single() }
assertFailsWith<RuntimeException> { flow.singleOrNull() }
assertFailsWith<IllegalArgumentException> { flow.single() }
assertNull(flow.singleOrNull())
}

@Test
Expand Down Expand Up @@ -61,6 +61,10 @@ class SingleTest : TestBase() {
assertEquals(1, flowOf<Int?>(1).single())
assertNull(flowOf<Int?>(null).single())
assertFailsWith<NoSuchElementException> { flowOf<Int?>().single() }

assertEquals(1, flowOf<Int?>(1).singleOrNull())
assertNull(flowOf<Int?>(null).singleOrNull())
assertNull(flowOf<Int?>().singleOrNull())
}

@Test
Expand Down