kotlinx.coroutines icon indicating copy to clipboard operation
kotlinx.coroutines copied to clipboard

Improve performance of SharingStarted.StartedLazily by changing flow to unsafeFlow

Open seyoungcho2 opened this issue 7 months ago • 0 comments
trafficstars

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 avatar Mar 24 '25 22:03 seyoungcho2