Skip to content

Commit e6c5361

Browse files
ansmanqwwdfsad
authored andcommitted
Allow nullable types in Flow's firstOrNull extension
This closes #2229
1 parent d2ed1d8 commit e6c5361

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

kotlinx-coroutines-core/common/src/flow/terminal/Reduce.kt

+3-3
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ public suspend fun <T> Flow<T>.first(predicate: suspend (T) -> Boolean): T {
112112
* The terminal operator that returns the first element emitted by the flow and then cancels flow's collection.
113113
* Returns `null` if the flow was empty.
114114
*/
115-
public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
115+
public suspend fun <T> Flow<T>.firstOrNull(): T? {
116116
var result: T? = null
117117
collectWhile {
118118
result = it
@@ -122,10 +122,10 @@ public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
122122
}
123123

124124
/**
125-
* The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
125+
* The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
126126
* Returns `null` if the flow did not contain an element matching the [predicate].
127127
*/
128-
public suspend fun <T : Any> Flow<T>.firstOrNull(predicate: suspend (T) -> Boolean): T? {
128+
public suspend fun <T> Flow<T>.firstOrNull(predicate: suspend (T) -> Boolean): T? {
129129
var result: T? = null
130130
collectWhile {
131131
if (predicate(it)) {

kotlinx-coroutines-core/common/test/flow/terminal/FirstTest.kt

+6
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,12 @@ class FirstTest : TestBase() {
128128
assertNull(emptyFlow<Int>().firstOrNull { true })
129129
}
130130

131+
@Test
132+
fun testFirstOrNullWithNullElement() = runTest {
133+
assertNull(flowOf<String?>(null).firstOrNull())
134+
assertNull(flowOf<String?>(null).firstOrNull { true })
135+
}
136+
131137
@Test
132138
fun testFirstOrNullWhenErrorCancelsUpstream() = runTest {
133139
val latch = Channel<Unit>()

0 commit comments

Comments
 (0)