How to get an attribute from a UI data class as a ...
# compose
a
How to get an attribute from a UI data class as a state in Composable? Say I have A class
Copy code
data class A(val x: Int)
Inside the Composable:
Copy code
@Composable
fun Test(vm: ViewModel){
  val a by vm.a.collectAsState()// I want x attribute not a object
}
Is there a way to accomplish that?
a
you can now write
a.x
where you wish to access the attribute
a
I know, but I want to use
x
to produce another value like:
Copy code
val a vm.a.collectAsState()
val isXEqualsToZero by remember {
     derivedStateOf { a.x == 0 }
}
It's more convenient to get rid of
a
and use
x
directly
a
then you can write
val x = a.x
first, or wrap you code in
with (a) {...}
there's no compose magic for this, its normal kotlin language behaviour
assuming a is a flow of some kind, you could also create another flow in your viewmodel that maps from a to x
then you could do
vm.x.collectAsState()
a
In that case, can I use it inside the
derivedStateOf
directly without creating another state for it? Idk if
snapShotFlow{}
can help in such cases
a
in what case?
a
That you mentioned,
x
in viewModel
a
im not sure what to tell you, if x is in the viewmodel you can do all the same things with it you can with a
wait this is silly
why do you need to remember
isXEqualsToZero
because a is state, you can just write
val isXEqualToZero = a.x == 0
it will work fine, and. update when a does
a
Thank you, idk how I missed that!
b
isXEqualToZero = a.X == 0 will recompose more than you probably want
remember/derivedStateOf is the way to go and will only update when the calculation inside changes
a
that screams premature optimisation to me, a small thing like that is basically guaranteed to not be a big deal unless a is changing very often
by that logic any and all conditional logic on data class state should be wrapped in derivedStateOf
b
Do you know what he’s doing with X to claim its “screaming” premature optimization?
a
the point is more that
derivedStateOf
is only necessary when performance improvements are needed. as is repeated throughout compose documentation when performance is involved, optimisations should not be undertaken without there being evidence of an actual performance hit. compose is performant by default in the vast majority of cases, so its not really correct to say that
derivedStateOf
is the way to go.
really its a premature optimisation by definition in this case
a
X
here is a state that changed by clicking a button
a
it so often is 😛
b
not really, no wrt "it so often is" but all good