Mokera

Tech Sheets

mokelab

How to use LaunchedEffect

Last updated:2024-07-10

Composable is a function. So you might want to write a code (side effects) at the time of display, like this:

@Composable
fun TopScreen(id: String) {
  // Let's fetch data from server!
  val user = getUser(id)
  
  Text(user.name)
}

However, Composable functions are called multiple times by state changes, etc. Also, since they are outside the coroutine scope, you cannot call suspend functions.

If you want to execute an action when a Composable is displayed, use LaunchedEffect .

@Composable
fun LaunchedEffectScreen(
    back: () -> Unit,
) {
    var counter by remember { mutableStateOf(0) }

    LaunchedEffect(Unit) {
        while (true) {
            delay(1000)
            ++counter
        }
    }

    // HasBackScaffold is a custom Composable
    HasBackScaffold(
        title = stringResource(id = R.string.effect_launched_effect),
        back = back,
    ) { paddingValues ->
        Text(
            "Count=${counter}",
            modifier = Modifier.padding(paddingValues)
        )
    }
}

The argument to LaunchedEffect is a key object. When the value of the key changes at re-Compose, the coroutine will be cancelled and restarted.

Back