Colton Idle
04/10/2022, 4:20 PMderivedStateOf
often but does this seem like a good use case? Bonus: Why can't I use by
and need to use =
when using derivedStateOf
?
class SignUpScreenViewState {
var email by mutableStateOf("")
var password by mutableStateOf("")
var acceptTerms by mutableStateOf(false)
var canMakeSignUpCall = derivedStateOf { email.isNotEmpty() && password.isNotEmpty() && acceptTerms }
}
Desmond Teo
04/10/2022, 4:20 PMColton Idle
04/10/2022, 4:22 PMFrancesc
04/10/2022, 4:24 PMFrancesc
04/10/2022, 4:26 PMColton Idle
04/10/2022, 4:26 PMFrancesc
04/10/2022, 4:27 PMNorbi
04/10/2022, 4:28 PMderivedstateOf()
? As I understand derivedStateOf()
should be used when the derived state is expensive to calculate. This is not the case in your example, in this case I would simple use a val
property without a backing field.
Eg., what I see as a valid usage for derivedStateOf()
, is sorting and filtering a List
with lots of elements...Francesc
04/10/2022, 4:29 PMremember
Francesc
04/10/2022, 4:30 PMFrancesc
04/10/2022, 4:31 PMNorbi
04/10/2022, 4:33 PMAs the filtering to calculatecan be expensive, it should only be executed when any of the lists change, not on every recomposition.highPriorityTasks
Norbi
04/10/2022, 4:35 PMAnd a simple val would not be observableWhat I meant was:
val canMakeSignUpCall get() = email.isNotEmpty() && password.isNotEmpty() && acceptTerms
Hmmm, do you mean that this would not work at all? (I'm almost sure that it would - but I cannot try it currently 🤔)Francesc
04/10/2022, 5:05 PMNorbi
04/10/2022, 5:08 PMFrancesc
04/10/2022, 5:23 PMAlbert Chang
04/10/2022, 11:48 PMemail
, password
or acceptTerms
changes. And the difference is also here: recomposition will happen whenever any of these three vars change, even if the result is the same, while a derived state will only trigger recomposition if the result of the calculation changes.Alex Vanyo
04/11/2022, 5:18 PMval
has a get() =
or not can make quite a difference in behavior. That isn’t Compose specific at all, but at least in my experience Compose makes me think about the difference way moreBen Trengrove [G]
04/11/2022, 9:48 PMremember { derivedStateOf {} }
as wellAlex Vanyo
04/11/2022, 10:28 PM@Composable
context you want the remember
, if you’re in a state holder class like this one just having a derivedStateOf
will be fine (there’s no remember
to use!)
Personally I’d probably go with the get() =
approach for this specific case, I’ve been erring on the side of not using derivedStateOf
unless it’s necessary for correctness or performance. But using derivedStateOf
here as written will also lead to correct behavior.Ben Trengrove [G]
04/11/2022, 11:43 PM