Side Effects & Lifecycle
Why side effects need care
Composables can run many times (recomposition). To run something once or in response to a key change, use effect APIs instead of calling it directly in the body.
LaunchedEffect
@Composable
fun Profile(userId: Int, vm: ProfileViewModel) {
LaunchedEffect(userId) {
vm.load(userId) // runs when userId changes
}
}
rememberCoroutineScope (event-driven)
val scope = rememberCoroutineScope()
Button(onClick = {
scope.launch { snackbarHostState.showSnackbar("Saved!") }
}) { Text("Save") }
Collecting state from a ViewModel
val uiState by viewModel.state.collectAsStateWithLifecycle()
Rule: never start coroutines or network calls directly in a composable body — wrap them in LaunchedEffect or an event handler.