Level 8
Side Effects
LaunchedEffect & Side Effects
Running code that isn't UI (timers, analytics, snackbars) inside Composable functions safely.
📚 Explanation
`LaunchedEffect` runs side effects (like API calls, timers) when a Composable enters composition or when keys change. `rememberCoroutineScope` provides a coroutine scope tied to the composition lifecycle for launching coroutines from callbacks.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
@Composablefun AutoSaveScreen(onSave: () -> Unit) {// launchedEffect runs ONCE when the component enters the screen// or when 'key1' changes.LaunchedEffect(Unit) {delay(5000) // Wait 5 secondsonSave()}// rememberCoroutineScope allows launching coroutines from callbacks (like onClick)val scope = rememberCoroutineScope()val snackbarHostState = remember { SnackbarHostState() }Button(onClick = {scope.launch {snackbarHostState.showSnackbar("Saved!")}}) {Text("Manual Save")}}