Is it better (performance, code quality, etc.) to do option a or b?
A:
Copy code
@Compose
fun Parent() {
var updatingValue by remember { mutableStateOf(0) }
LaunchedEffect(Unit) {
while(isActive) {
delay(1_000)
updatingValue += 1
}
}
repeat(10) { Child(updatingValue) }
}
@Compose
fun Child(updatingValue: Int) {
Text(updatingValue.toString())
}
B:
Copy code
@Compose
fun Parent() {
repeat(10) { Child() }
}
@Compose
fun Child() {
var updatingValue by remember { mutableStateOf(0) }
LaunchedEffect(Unit) {
while(isActive) {
delay(1_000)
updatingValue += 1
}
}
Text(updatingValue.toString())
}
👍 1
f
Francesc
07/10/2023, 12:56 AM
these are not equivalent,. On A you have 1 state shared by 10 composables, while in B you have 10 composables with each their own state
e
ephemient
07/10/2023, 1:02 AM
moreover, there's nothing guaranteeing that the 10 independent states stay in sync with each other
r
Rob
07/10/2023, 1:43 AM
Also the business logic of updating the value should be done in the domain or data layers and not in the UI layer. UI layer should turn ViewModel state into Composable states.
s
Sam Stone
07/10/2023, 11:25 AM
So is this the completely wrong way to do it? Assume for arguments sake that staying in sync is not an issue. How should it be changed?
r
Rob
07/10/2023, 8:49 PM
Having a
MutableStateFlow<Int>
in your Android ViewModel. Expose immutable
StateFlow<Int>
using
asStateFlow()
. Observe the
StateFlow<Int>
using
collectAsStateWithLifecycle()
at beginning of
setContent
of ComposeView and only send immutable data to Composables. Update the ViewModel state by sending events to the ViewModel.