What’s the recommendation around using `derivedSta...
# compose
j
What’s the recommendation around using
derivedStateOf
? Is it safe and or efficient to “nest” calls ie call another
derivedStateOf
property inside the
calculation
block? Is there a diminishing returns on nesting? Will there be recomposition delays by heavily nesting?
Working example:
Copy code
val opp by derivedStateOf { distance(vertexB, vertexC) }

val adj by derivedStateOf { distance(vertexA, vertexC) }

val hyp by derivedStateOf { distance(vertexA, vertexB) }

val sin by derivedStateOf { opp / hyp }

val cos by derivedStateOf { adj / hyp }

val tan by derivedStateOf { opp / adj }
The properties
vertextA
,
vertextB
,
vertextC
are also
derivedStateOf
properties… This currently works but I’m concerned that I’m introducing subtle bugs and I don’t realize it.
r
If the distance function does what I think it does, none of those derivedStateOf are useful. These computations are trivial enough
j
What do you mean useful?
distance
is just a call to
Math.hypot(...)
r
Right so the cost of derivedStateOf is going to be greater than just doing the computation always
(even more so for the simple divisions you have)
j
I see.. The vertex variables are
mutableStateOf
because I set them from my Composable when the I detect taps/drags. Wouldn't I need "derived" state to allow calling code to observe changes to trig info?
r
Using derivedStateOf would make sense if the rate of change of the derived state is (very) different from the rate of change of the source state
In your case changing a vertex will always change the distance, so there's no benefit
The cost/sin/tan angles might change at a different rate but I'd be surprised if it's meaningful anyway
j
Should I just make these simple computed properties?
r
Indeed
j
Will this be sufficient for other composable code to observe changes to
tan
or
cos
since they are not
State
?
s
You don't have to call state directly in the Composable code for it to be observable As long as state.value is called somewhere inside the function, even deep on the call stack (e.g. params to trig functions), it is going to be observed For example, that's how LazyListState scroll index/offset works