Skip to content
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

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

Merged

Conversation

francescotescari
Copy link
Contributor

Fix for #4322

@@ -340,6 +341,9 @@ private fun <T> CoroutineScope.launchSharingDeferred(
}
}
}
if (state == null) {
result.completeExceptionally(NoSuchElementException("Flow is empty"))
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Notice: I think we shouldn't cancel the collecting scope here, as there is nothing wrong with the flow collection itself, the exception should be limited to stateIn IMHO.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, good point, let's not cancel the collecting scope. This is tricky to do ensure cleanly, though! Here's a slightly convoluted solution:

    /* If `scope`'s job is cancelled, both `deferredParentJob` and the deferred will be cancelled.
    If the deferred is cancelled, this will not cancel `deferredParentJob` (as it's a `SupervisorJob`),
    and `CoroutineExceptionHandler` present in `scope` (if any) won't get invoked,
    as `Deferred` values are themselves responsible for propagating their exceptions. */
    val deferredParentJob = SupervisorJob(scope.coroutineContext[Job])
    val result = CompletableDeferred<StateFlow<T>>(deferredParentJob)
    scope.launchSharingDeferred(config.context, config.upstream, result)
    return try {
        result.await()
    } finally {
        deferredParentJob.cancel()
    }

then the modified test is:

    @Test
    fun testThrowsNoSuchElementExceptionOnEmptyFlow() = runTest {
        val flow = emptyFlow<Any>()
        assertFailsWith<NoSuchElementException> {
            flow.stateIn(this)
        }
        assertEquals(true, coroutineContext[Job]?.isActive)
        coroutineContext.cancelChildren()
    }

(Note this runTest is not kotlinx.coroutines.test.runTest!) If the main coroutine of runTest gets cancelled, the whole test fails; also, if there are any uncaught exceptions in child coroutines of runTest, they do get reported at the end of the test. So, this test does check that NoSuchElementException doesn't propagate upwards.

The only other option I see is to rely on our internal low-level job.invokeOnCompletion function to avoid the parent-child relationship between scope and result altogether. After implementing that option, I don't like how it recreates parts of child cancellation logic. This looks like a weird micro-optimization.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another simpler (not elegant) trick is to make CompletableDeferred of type CompletableDeferred<Result<StateFlow<T>>> and complete the deferred successfully but with Result.failure and unpack with getOrThrow it stateIn side.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Good idea!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@francescotescari, would you like to implement this, or should I do it?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry for the delay, addressed it now.
LMK if it looks good to you 🙏

@dkhalanskyjb dkhalanskyjb merged commit 03b81f4 into Kotlin:develop Feb 12, 2025
@dkhalanskyjb
Copy link
Collaborator

Thank you both for the bug report and a well-thought-out fix!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants