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

Add StateFlow<T>.onSubscription #4275

Open
xit0c opened this issue Nov 15, 2024 · 4 comments
Open

Add StateFlow<T>.onSubscription #4275

xit0c opened this issue Nov 15, 2024 · 4 comments

Comments

@xit0c
Copy link

xit0c commented Nov 15, 2024

Use case

The current SharedFlow<T>.onSubscription implementation returns a SharedFlow<T>, which means losing type information when calling it from a StateFlow<T>. It would be nice to have a StateFlow<T>.onSubscription counterpart for StateFlow<T>, thus avoiding the aforementioned issue.

The Shape of the API

Unless there are implementation details I'm unaware of, the API could be copy-pasted from the SharedFlow<T>.onSubscription implementation and adapted to work with StateFlow<T>:

public fun <T> StateFlow<T>.onSubscription(action: suspend FlowCollector<T>.() -> Unit): StateFlow<T> =
    SubscribedStateFlow(this, action)

@OptIn(ExperimentalForInheritanceCoroutinesApi::class)
private class SubscribedStateFlow<T>(
    private val stateFlow: StateFlow<T>,
    private val action: suspend FlowCollector<T>.() -> Unit
) : StateFlow<T> by stateFlow {
    override suspend fun collect(collector: FlowCollector<T>) =
        stateFlow.collect(SubscribedFlowCollector(collector, action))
}

Prior Art

@dkhalanskyjb
Copy link
Collaborator

Sure, this makes sense, thanks! Would you like to open a PR with this code (+ documentation + tests)?

@qwwdfsad qwwdfsad added the flow label Feb 28, 2025
@xit0c
Copy link
Author

xit0c commented Mar 3, 2025

I'd be glad to! I hope to deliver the changes in the next few days.

xit0c added a commit to xit0c/kotlinx.coroutines that referenced this issue Mar 9, 2025
@xit0c
Copy link
Author

xit0c commented Mar 9, 2025

Done!

The documentation is copy-pasted from SharedFlow.onSubscription, I've only replaced the word "shared" with "state" in the first line.

About the tests, I saw that there's already testOnSubscriptionWithException (which now is using the new onSubscription), is it enough?

@dkhalanskyjb
Copy link
Collaborator

Good job, thanks! Let's continue under #4380, as this starts to be about the implementation and not the issue itself.

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

No branches or pull requests

3 participants