Skip to content

Improve performance of SharingStarted.StartedLazily by changing flow to unsafeFlow #4393

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

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

seyoungcho2
Copy link
Contributor

@seyoungcho2 seyoungcho2 commented Mar 24, 2025

In this case, StartLazily uses flow, but since it simply collects subscriptionCount and processes it, there is no need to use SafeFlow and consume additional resources for context checks.

private class StartedLazily : SharingStarted {
    override fun command(subscriptionCount: StateFlow<Int>): Flow<SharingCommand> = flow { 
        var started = false
        subscriptionCount.collect { count ->
            if (count > 0 && !started) {
                started = true
                emit(SharingCommand.START)
            }
        }
    }

    override fun toString(): String = "SharingStarted.Lazily"
}

In other words, because it only collects data from another Flow and passes it along without executing any custom logic which switches coroutine context(similar to operators like map or filter), it can use unsafeFlow to skip context checks and reduce computing resource usage.

private class StartedLazily : SharingStarted {
    override fun command(subscriptionCount: StateFlow<Int>): Flow<SharingCommand> = unsafeFlow {
        var started = false
        subscriptionCount.collect { count ->
            if (count > 0 && !started) {
                started = true
                emit(SharingCommand.START)
            }
        }
    }

    override fun toString(): String = "SharingStarted.Lazily"
}

@seyoungcho2 seyoungcho2 force-pushed the feature/improve-start-lazily branch from 64ef375 to a5edd29 Compare March 25, 2025 00:37
@seyoungcho2 seyoungcho2 force-pushed the feature/improve-start-lazily branch from a5edd29 to d5bdf6f Compare March 25, 2025 00:38
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.

1 participant