kotlinx.coroutines
kotlinx.coroutines copied to clipboard
Improve performance of SharingStarted.StartedLazily by changing flow to unsafeFlow
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"
}