0
0
Android Kotlinmobile~7 mins

Side effects (LaunchedEffect, SideEffect) in Android Kotlin

Choose your learning style9 modes available
Introduction

Side effects let your app do things outside of just showing UI, like loading data or logging. They help your app react to changes safely.

When you want to load data from the internet after the screen appears.
When you need to save user actions to a log or analytics service.
When you want to show a message once after a button is clicked.
When you want to run code only once when a screen is first shown.
When you want to update something outside the UI based on state changes.
Syntax
Android Kotlin
LaunchedEffect(key) {
    // suspend functions or side effect code here
}

SideEffect {
    // code that runs after every successful recomposition
}

LaunchedEffect runs suspend functions and cancels/restarts if the key changes.

SideEffect runs after every UI update but does not support suspend functions.

Examples
This runs once when the screen appears because the key is Unit (constant).
Android Kotlin
LaunchedEffect(Unit) {
    println("Screen appeared")
}
This reloads user data whenever userId changes.
Android Kotlin
LaunchedEffect(userId) {
    loadUserData(userId)
}
This prints a message after every UI update.
Android Kotlin
SideEffect {
    println("UI updated")
}
Sample App

This app shows a button with a click count. When you click, count changes.

LaunchedEffect prints a message only when count changes.

SideEffect prints a message every time the UI updates.

Android Kotlin
import androidx.compose.runtime.*
import androidx.compose.material3.*
import androidx.compose.ui.window.singleWindowApplication

fun main() = singleWindowApplication {
    var count by remember { mutableStateOf(0) }

    LaunchedEffect(count) {
        println("Count changed to $count")
    }

    SideEffect {
        println("UI recomposed with count = $count")
    }

    Button(onClick = { count++ }) {
        Text("Clicked $count times")
    }
}
OutputSuccess
Important Notes

Use LaunchedEffect for suspend functions like network calls.

SideEffect is good for quick updates like logging or updating external variables.

Keys in LaunchedEffect control when the effect restarts.

Summary

Side effects let your app do work outside just showing UI.

LaunchedEffect runs suspend code and restarts on key changes.

SideEffect runs after every UI update for quick side tasks.