Skip to content

Flow firstOrNull support #1796

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

Closed
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
2 changes: 2 additions & 0 deletions kotlinx-coroutines-core/api/kotlinx-coroutines-core.api
Original file line number Diff line number Diff line change
Expand Up @@ -900,6 +900,8 @@ public final class kotlinx/coroutines/flow/FlowKt {
public static final fun filterNotNull (Lkotlinx/coroutines/flow/Flow;)Lkotlinx/coroutines/flow/Flow;
public static final fun first (Lkotlinx/coroutines/flow/Flow;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public static final fun first (Lkotlinx/coroutines/flow/Flow;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public static final fun firstOrNull (Lkotlinx/coroutines/flow/Flow;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public static final fun firstOrNull (Lkotlinx/coroutines/flow/Flow;Lkotlin/jvm/functions/Function2;Lkotlin/coroutines/Continuation;)Ljava/lang/Object;
public static final fun flatMap (Lkotlinx/coroutines/flow/Flow;Lkotlin/jvm/functions/Function2;)Lkotlinx/coroutines/flow/Flow;
public static final fun flatMapConcat (Lkotlinx/coroutines/flow/Flow;Lkotlin/jvm/functions/Function2;)Lkotlinx/coroutines/flow/Flow;
public static final fun flatMapLatest (Lkotlinx/coroutines/flow/Flow;Lkotlin/jvm/functions/Function2;)Lkotlinx/coroutines/flow/Flow;
Expand Down
36 changes: 36 additions & 0 deletions kotlinx-coroutines-core/common/src/flow/terminal/Reduce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -120,3 +120,39 @@ public suspend fun <T> Flow<T>.first(predicate: suspend (T) -> Boolean): T {
if (result === NULL) throw NoSuchElementException("Expected at least one element matching the predicate $predicate")
return result as 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? {
var result: Any? = NULL
try {
collect { value ->
result = value
throw AbortFlowException(NopCollector)
}
} catch (e: AbortFlowException) {
// Do nothing
}
return result.takeUnless { it == NULL } as T?
}

/**
* The terminal operator that returns the first element emitted by the flow 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? {
var result: Any? = NULL
try {
collect { value ->
if (predicate(value)) {
result = value
throw AbortFlowException(NopCollector)
}
}
} catch (e: AbortFlowException) {
// Do nothing
}
return result.takeUnless { it == NULL } as T?
}
67 changes: 67 additions & 0 deletions kotlinx-coroutines-core/common/test/flow/terminal/FirstTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -83,4 +83,71 @@ class FirstTest : TestBase() {
assertEquals(1, flow.first())
finish(2)
}

@Test
fun testFirstOrNull() = runTest {
val flow = flowOf(1, 2, 3)
assertEquals(1, flow.firstOrNull())
}

@Test
fun testFirstOrNullWithPredicate() = runTest {
val flow = flowOf(1, 2, 3)
assertEquals(1, flow.firstOrNull { it > 0 })
assertEquals(2, flow.firstOrNull { it > 1 })
assertNull(flow.firstOrNull { it > 3 })
}

@Test
fun testFirstOrNullCancellation() = runTest {
val latch = Channel<Unit>()
val flow = flow {
coroutineScope {
launch {
latch.send(Unit)
hang { expect(1) }
}
emit(1)
emit(2)
}
}


val result = flow.firstOrNull {
latch.receive()
true
}
assertEquals(1, result)
finish(2)
}

@Test
fun testFirstOrNullWithEmptyFlow() = runTest {
assertNull(emptyFlow<Int>().firstOrNull())
assertNull(emptyFlow<Int>().firstOrNull { true })
}

@Test
fun testFirstOrNullWhenErrorCancelsUpstream() = runTest {
val latch = Channel<Unit>()
val flow = flow {
coroutineScope {
launch {
latch.send(Unit)
hang { expect(1) }
}
emit(1)
}
}

assertFailsWith<TestException> {
flow.firstOrNull {
latch.receive()
throw TestException()
}
}

assertEquals(1, flow.firstOrNull())
finish(2)
}
}