Learning Android Development

Jetpack Compose Side Effects Made Easy

Linking the relationship of all Jetpack Compose side effects

Image by Kindel Media on Pexels

Understanding Jetpack Compose Side Effects is essential for one to use Jetpack Compose effectively to get it to work with non-compose elements of our App code.

There are many of them. I try to illustrate each of themwith simple examples below, with the hope we can easily know when to use what.

LaunchedEffect

Let’s start with the most common one LaunchedEffect.

This side effect will only be launched on the first composition. It will not relaunch on the recomposition. Nonetheless, we can get it run with the change of provided Key.

It is also a coroutine scope, where we can run suspend function within. Whatever run within will be canceled when exiting the composable function.

At times, we can use LaunchedEffect to act as a loop timer by having a while(true) within. The below code is an example where every second, it will increment the timer, which will cause the composable function to recompose itself.

@Composable
fun JustLaunchEffect() {
var timer by remember { mutableStateOf(0) }
Box(modifier =…

--

--