Handling Side-Effects in Jetpack Compose

8 min read Handling Side-Effects in Jetpack Compose October 07, 2024 19:23 Handling Side-Effects in Jetpack Compose Handling Side-Effects in Jetpack Compose

Handling Side-Effects in Jetpack Compose

In Android apps, side-effects are tasks like fetching data from the internet or listening to sensors that happen behind the scenes while the app updates the screen. In Jetpack Compose, handling these tasks is easy with tools like LaunchedEffect, rememberUpdatedState, SideEffect, and DisposableEffect.

1. LaunchedEffect: Running a Task When the Screen Loads

LaunchedEffect triggers something important (like fetching data) when a screen first appears.


@Composable
fun FetchDataEffect() {
    LaunchedEffect(Unit) {
        delay(1000)
        Log.d("LaunchedEffect", "Data fetched!")
    }
    Text(text = "Fetching data...")
}
    

In Simple Terms: The screen says "Fetching data..." while it waits a second before grabbing it.

2. rememberUpdatedState: Keeping Data Fresh

This ensures background tasks always use the latest information, even if things change during the task.


@Composable
fun TimerEffect(onTimeout: () -> Unit) {
    val currentOnTimeout by rememberUpdatedState(onTimeout)

    LaunchedEffect(Unit) {
        delay(3000)
        currentOnTimeout()
    }

    Text(text = "Waiting for timeout...")
}
    

In Simple Terms: After 3 seconds, the latest action will run, even if the screen changes.

3. SideEffect: Running Code on Every Screen Update

SideEffect runs every time the screen updates, useful for logging or tracking actions.


@Composable
fun LogOnRecompose(counter: Int) {
    SideEffect {
        Log.d("SideEffect", "Recomposed with counter: $counter")
    }

    Text(text = "Counter: $counter")
}
    

In Simple Terms: Whenever the counter changes, the app logs it.

4. DisposableEffect: Cleaning Up When the Screen Closes

DisposableEffect helps you clean up resources when the screen disappears, like stopping a sensor to save battery.


@Composable
fun SensorEffect(sensorManager: SensorManager) {
    DisposableEffect(Unit) {
        val listener = SensorEventListener { }
        sensorManager.registerListener(listener)

        onDispose {
            sensorManager.unregisterListener(listener)
        }
    }

    Text(text = "Listening to sensor...")
}
    

In Simple Terms: Start listening to the sensor when the screen shows up and stop when it closes to save resources.

Conclusion

Side-effects in Jetpack Compose ensure your app runs tasks properly behind the scenes, whether it's fetching data, logging info, or cleaning up resources.

#AndroidDevelopment #JetpackCompose #MobileDevelopment #SideEffects #ComposeTips #AppDevelopment #Tech #UI

User Comments (0)

Add Comment
We'll never share your email with anyone else.