https://kotlinlang.org logo
Title
v

Vadim Kapustin

11/13/2020, 11:53 AM
At first glance, MutableState and MutableStateFlow work equally well in Composable. What is better to use?
🤔 1
a

Animesh Sahu

11/13/2020, 12:27 PM
In my observations/opinion, the Compose compiler plugin generates some stubs to redraws only things whose state have been changed. You can always collect a state flow with a
.collectAsState()
to get state representation of the StateFlow. As far as I understood, every event fires redraw event of all the children UI elements, but only whose state changed actually gets executed and changed. When using a StateFlow, and directly calling
StateFlow.value
you'll be redrawing the UI for every single event like mouse move, mouse enter, mouse click, to the element you are using it with, even if the value wasn't changed.
I'm not so sure about this, but I think I'm correct according to use-case I've observed here:

https://www.youtube.com/watch?v=DDd6IOlH3io?t=5m56s

(timestamp: 5min 56sec)
v

Vadim Kapustin

11/13/2020, 1:08 PM
I don't seem to understand their mechanisms. I made an experiment to check the repetition of redrawing when the value did not change and got no redrawing at all even when the value changed... I'll look at this in more detail
Thanks for reply 🙂
g

gildor

11/13/2020, 1:36 PM
Have you checkedJetpack Compse doc? Path way is very good starting point https://developer.android.com/courses/pathways/compose
Your right, they are similat, observable state holder, but with own api and different use case
z

Zach Klippenstein (he/him) [MOD]

11/13/2020, 3:33 PM
I would reach for Flow-based tools first, since they rely on less magic and are easier to test with, imo. It also keeps the non-compose bits of your code compose-free, which can make it easier to refactor modules later on.
👍 2
s

Shawn Witte

11/13/2020, 5:55 PM
For everything outside of a
@Compose
function, I use
Flow
(or whichever subclass is appropriate, e.g.
StateFlow
), because
Flow
is fairly universal. However, the first few lines of my
@Compose
functions all convert those to
State
via
collectAsState()
because I know the composables will properly handle updates to
State
.
👍 4