Why is LaunchedEffect(true) suspicious?

Viewed 674

I'm working on implementing MVI using compose. In order for me to follow the proper event loop, I need to propagate clicks events through my view model and then observe side effects. I have looked at a few implementations and they all use LaunchedEffect(true) to observe side effects and take actions.

I have a similar setup for example:

@Composable
fun HelloComposeScreen(
    viewModel: MyViewModel = hiltViewModel(),
    onClickedNext: () -> Unit
) {
    LaunchedEffect(true) {
        viewModel.sideEffect.collectLatest { sideEffect ->
            when (sideEffect) {
                DashboardSideEffect.CreateParty -> onClickedNext()
            }
        }
    }
    Button(
        onClick = { viewModel.onEvent(UserEvent.ClickedButton)},
    ) {
        Text("Click Me")
    }
}

This results in me using LaunchedEffect(true) for any screen that has navigation or one time events but the official documentation has this warning

Warning: LaunchedEffect(true) is as suspicious as a while(true). Even though there are valid use cases for it, always pause and make sure that's what you need.

My questions are:

  • When exactly does the LaunchedEffect get canceled? The documentation says that it matches the lifecycle of the call site. Is that the composition in this case?
  • Considering that the official documentation has a warning there? Should I not be using this LaunchedEffect(true) setup for observing side effects through my project? What would be an alternative?
1 Answers

The LaunchedEffect is canceled along with its coroutine in two variants:

  1. The passed key argument(s) is changed - in this case the current LaunchedEffect will be cancelled and a new one will be created.
  2. LaunchedEffect is removed from the life tree, for example, in case you put it (or its parent at any level) in an if block and the condition becomes false.

If you do not need to pass any key that should restart LaunchedEffect, you can pass Unit. Any other constant, like true in your case, is considered suspect because it cannot be changed at runtime and yet may look like complex logic to any coder.

Related