Hi :wave:, I just want to ensure I understand corr...
# coroutines
h
Hi 👋, I just want to ensure I understand correctly the difference between hot flow and cold flow. Even though we use State flows that are hot, operators like
map
,
filter
or
combine
make hot flow cold, because their internal implementation is basically this:
Copy code
return flow {
    collect { value ->
        emit(transform(value))
    }
}
So, are the following examples correct?
Copy code
val stateFlowA = MutableStateFlow("A") 
val flowA: Flow<String> = stateFlowA // Is Hot flow

val stateFlowB = MutableStateFlow("B")
val flowB: Flow<String> = stateFlowB.map { it } // Is Cold flow

val flowC: Flow<String> = combine(stateFlowA, stateFlowB) { a, b -> "$a $b" } // Is Cold flow
Thank you 🙏
c
Yes
thank you color 1
You can make them hot again with
.sharedIn
or
.stateIn
s
Not sure if I agree 😀 I thought that • a cold flow/observable doesn't emit values unless there's at least one observer/subscriber/collector • a hot flow/observable emits values even if there are no observers/subscribers/collectors. With a 'map', or without a 'map', the ones in your example stay hot, since "emit" can be executed on both the original flow and the flow returned by 'map', whether anyone is listening or not...
c
If you add a
println
in the
.map
, you'll see it isn't executed until someone subscribes, so it's cold
s
Yup, you're right. Just tried it out. When adding a println statement even before the collect call, it's printing something only after something else starts collecting that mapped one.
z
The terminology is maybe what’s confusing. Using these operators don’t change the upstream flow. The returned flow is kind of both hot and cold, depending on where in the flow you’re observing. So it depends on context whether the single term “hot”/“cold” is enough to actually communicate adequately.
👍 2