What's the simplest way to transform a `StateFlow`...
# coroutines
d
What's the simplest way to transform a
StateFlow
into a different one? This is what I've done, not sure if it's the best or even working...
Copy code
val newStateFlow = originalStateFlow
        .map { it.doTransform() }
        .stateIn(scope = CoroutineScope(Job()), started = SharingStarted.Eagerly, initialValue = false)
j
You should never create a CoroutineScope on the fly like this without storing it into a variable. You need to control the cancellation of the coroutines that it manages by cancelling this scope at an appropriate time. Converting any flow into a state flow implies that a coroutine collects the source flow to update the state, and that work needs to stop when not needed anymore (state flows are hot)
Apart from that, I guess it's the correct way
d
Thank you. It's used in a singleton and is intended to exist for the lifetime of the application.
j
Then this is a good use case for using
GlobalScope
(maybe even the only good use case?)
👍 1