https://kotlinlang.org logo
#compose
Title
# compose
d

Daniele B

06/11/2020, 7:56 PM
can anyone suggest any article/sample showing how JetpackCompose can be used with StateFlow?
d

Daniele B

06/11/2020, 8:04 PM
that’s very interesting! so is it that easy to make a component “listen” to a StateFlow?!
v

Vinay Gaba

06/11/2020, 8:07 PM
Yeah pretty much!
collectAsState
converts it to a form that compose understands (
state
) and is able to listen to the stream seamlessly.
d

Daniele B

06/11/2020, 8:10 PM
Wow! it’s really amazing! Thanks for showing it to me
I was looking for a simple example online, but I could not find it
did you have any chance to play with StateFlow and SwiftUI in a KotlinMultiplatform context?
I wish it was so simple too, but I doubt it 😄
v

Vinay Gaba

06/11/2020, 8:14 PM
I’ve not dabbled with SwiftUI yet but it’s definitely something I will hopefully do at some point 😄
d

Daniele B

06/11/2020, 8:15 PM
great! let’s keep in touch then, I will be working on a multiplatform project in the next months
v

Vinay Gaba

06/11/2020, 8:15 PM
excited to see your progress!
d

Daniele B

06/11/2020, 8:16 PM
thanks! 👍
you gave me a very clear starting point, I am very glad
Hi Vinay, I have a question about your sample. Is “initial” a special keyword?
is it specific of Flow?
v

Vinay Gaba

06/11/2020, 9:27 PM
that’s just a named parameter to the collectAsState method.
d

Daniele B

06/11/2020, 9:28 PM
perfect! that’s clear now
thanks!
v

Vinay Gaba

06/11/2020, 9:29 PM
🙌🏼
d

Daniele B

06/11/2020, 9:31 PM
@Vinay Gaba I actually realized you are using Flow instead of StateFlow. Is there a specific reason?
as far as I understand StateFlow is a hot flow, while Flow is a cold flow
which is the effect of using Flow instead of StateFlow inside a Composable?
I was reading that: “StateFlow only returns if the value has updated and doesn’t return the same value. In simpler terms, consider two values x and y where x is the value initially emitted and y is the value to be emitted. StateFlow makes sure, if 
(x == y)
 the do nothing but if 
(x !=y)
 then only emit the new value i.e. y in this case.”
z

Zach Klippenstein (he/him) [MOD]

06/11/2020, 10:12 PM
As far as the consumer is concerned, the only difference between
Flow
and
StateFlow
is that you can ask a
StateFlow
for its current value without collecting it, and it will always immediately emit a value when collected.
That’s why the
StateFlow.collectAsState()
doesn’t require you to pass in an initial value, but
Flow.collectAsState
does.
as far as I understand StateFlow is a hot flow, while Flow is a cold flow
Not exactly. A
Flow
can be hot as well, since
StateFlow
is a subtype of
Flow
. The types don’t necessarily imply anything about their “temperature”.
Unlike
Flow
vs
Channel
, where
Channel
is always hot.
d

Daniele B

06/11/2020, 10:51 PM
@Zach Klippenstein (he/him) [MOD] thanks for the explanation! it’s clear now