Is it better (performance, code quality, etc.) to ...
# compose
s
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
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
moreover, there's nothing guaranteeing that the 10 independent states stay in sync with each other
r
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
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
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.
And depending how much deeper your logic goes you may want to have a repository/data layer. https://developer.android.com/topic/architecture