Why can't we `.map` a `StateFlow` and have it stil...
# flow
a
Why can't we
.map
a
StateFlow
and have it still be a
StateFlow
? Why the conversion to a regular
Flow
?
c
Because
.map
can suspend, the child flow needs its own scope. You can convert a flow into a StateFlow with
.stateIn
.
🙏 2
c
I asked the same question a month ago, but once I thought about it I realized it didn’t make sense to map a StateFlow to another StateFlow: https://kotlinlang.slack.com/archives/CRJCTR5PD/p1626814749057400
For example, consider the following code:
Copy code
val numberFlow = MutableStateFlow<Int>(0)

val lessThanZero = numberFlow.filter { it < 0 }

// Suppose for a moment that filter/map could return a StateFlow, how would the below work:
val currentValue = lessThanZero.value

// What's the value of currentValue?
🙏 1
a
@Chris Fillmore yeah, for
.filter
this is easy, but for
map
its harder to see, since map will always return a value.
map
being able to suspend solves the question because then it might suspend for a while (on first submision) in which no value is present in the resulting stateflow, which is not allowed.
👍 1