Skip to content

fix: handle cancelled scope and empty flow in Flow.stateIn #4327

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
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
12 changes: 8 additions & 4 deletions kotlinx-coroutines-core/common/src/flow/operators/Share.kt
Original file line number Diff line number Diff line change
Expand Up @@ -317,29 +317,33 @@ public fun <T> Flow<T>.stateIn(
* with multiple downstream subscribers. See the [StateFlow] documentation for the general concepts of state flows.
*
* @param scope the coroutine scope in which sharing is started.
* @throws NoSuchElementException if the upstream flow does not emit any value.
*/
public suspend fun <T> Flow<T>.stateIn(scope: CoroutineScope): StateFlow<T> {
val config = configureSharing(1)
val result = CompletableDeferred<StateFlow<T>>()
val result = CompletableDeferred<Result<StateFlow<T>>>(scope.coroutineContext[Job])
scope.launchSharingDeferred(config.context, config.upstream, result)
return result.await()
return result.await().getOrThrow()
}

private fun <T> CoroutineScope.launchSharingDeferred(
context: CoroutineContext,
upstream: Flow<T>,
result: CompletableDeferred<StateFlow<T>>
result: CompletableDeferred<Result<StateFlow<T>>>,
) {
launch(context) {
try {
var state: MutableStateFlow<T>? = null
upstream.collect { value ->
state?.let { it.value = value } ?: run {
state = MutableStateFlow(value).also {
result.complete(ReadonlyStateFlow(it, coroutineContext.job))
result.complete(Result.success(ReadonlyStateFlow(it, coroutineContext.job)))
}
}
}
if (state == null) {
result.complete(Result.failure(NoSuchElementException("Flow is empty")))
}
} catch (e: Throwable) {
// Notify the waiter that the flow has failed
result.completeExceptionally(e)
Expand Down
20 changes: 20 additions & 0 deletions kotlinx-coroutines-core/common/test/flow/sharing/StateInTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package kotlinx.coroutines.flow
import kotlinx.coroutines.testing.*
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.*
import kotlin.coroutines.*
import kotlin.test.*

/**
Expand Down Expand Up @@ -88,4 +89,23 @@ class StateInTest : TestBase() {
fun testSubscriptionByFirstSuspensionInStateFlow() = runTest {
testSubscriptionByFirstSuspensionInCollect(flowOf(1).stateIn(this@runTest)) { }
}

@Test
fun testRethrowsCEOnCancelledScope() = runTest {
val cancelledScope = CoroutineScope(EmptyCoroutineContext).apply { cancel("CancelMessageToken") }
val flow = flowOf(1, 2, 3)
assertFailsWith<CancellationException>("CancelMessageToken") {
flow.stateIn(cancelledScope)
}
}

@Test
fun testThrowsNoSuchElementExceptionOnEmptyFlow() = runTest {
val flow = emptyFlow<Any>()
assertFailsWith<NoSuchElementException> {
flow.stateIn(this)
}
// Ensure that the collecting scope is not cancelled by the NoSuchElementException
assertEquals(true, coroutineContext[Job]?.isActive)
}
}