Using side-effects with Jetpack Compose
With side-effects in Jetpack Compose, you can run non-UI tasks outside the composable. This separates UI rendering and non-UI operations, making the app more responsive and the code more organized. For example, you can perform a network operation only on the first load of the screen and not on every recomposition.
Jetpack Compose has several Composable functions that allow you to manage side effects, such as LaunchedEffect
, DisposableEffect
, and SideEffect
.
LaunchedEffect
LaunchedEffect
, when entering the composition, runs a coroutine with the block passed. This coroutine will be canceled when LaunchedEffect
leaves the composition. On recomposition, it will only recompose when the key/s change. LaunchedEffect
is useful when you want to do network, database, or other long-running tasks.
You can pass one or more keys that will determine whether the code inside LaunchedEffect
will be recomposed. Using LaunchedEffect(Unit)
will ensure...