https://kotlinlang.org logo
#flow
Title
# flow
a

Alex

08/31/2021, 10:39 AM
Why can't we
.map
a
StateFlow
and have it still be a
StateFlow
? Why the conversion to a regular
Flow
?
c

CLOVIS

08/31/2021, 10:49 AM
Because
.map
can suspend, the child flow needs its own scope. You can convert a flow into a StateFlow with
.stateIn
.
🙏 2
c

Chris Fillmore

09/01/2021, 1:00 AM
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

Alex

09/01/2021, 8:11 AM
@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
3 Views