DEV Community


Posted on

Jetpack Compose Lifecycle

composable function is the replacement for xml files .
in classic way you use to handle many activity or fragment lifecycle.

so we focus on View lifecycle because there are many components in android that have their own lifecycle

> The lifecycle of a composable is defined by the following events: entering the Composition, getting recomposed 0 or more times, and leaving the Composition.

Image description

so here we treat something called Composition :)

so composable function has three lifecycle:

 -  enter composition
 -  recomposition n times
 -   leave composition
Enter fullscreen mode Exit fullscreen mode

to observe your composable function's lifecycle you have to use class called State

> Recomposition is typically triggered by a change to a State object. Compose tracks these and runs all composables in the Composition that read that particular State, and any composables that they call that cannot be skipped.

to understand lifecycle also we need to know about Side-Effects methods in compose

> A side-effect is a change to the state of the app that happens outside the scope of a composable function.

> An effect is a composable function that doesn't emit UI and causes side effects to run when a composition completes.

there are many side-Effect function in compose


run suspend functions in the scope of a composable

fun MyScreen(
state: UiState>,
scaffoldState: ScaffoldState = rememberScaffoldState()
) {

// If the UI state contains an error, show snackbar
if (state.hasError) {

    // `LaunchedEffect` will cancel and re-launch if
    // `scaffoldState.snackbarHostState` changes
    LaunchedEffect(scaffoldState.snackbarHostState) {
        // Show snackbar using a coroutine, when the coroutine is cancelled the
        // snackbar will automatically dismiss. This coroutine will cancel whenever
        // `state.hasError` is false, and only start when `state.hasError` is true
        // (due to the above if-check), or if `scaffoldState.snackbarHostState` changes.
            message = "Error message",
            actionLabel = "Retry message"

Scaffold(scaffoldState = scaffoldState) {
    /* ... */
Enter fullscreen mode Exit fullscreen mode



obtain a composition-aware scope to launch a coroutine `outside a composable

fun MoviesScreen(scaffoldState: ScaffoldState = rememberScaffoldState()) {

// Creates a CoroutineScope bound to the MoviesScreen's lifecycle
val scope = rememberCoroutineScope()

Scaffold(scaffoldState = scaffoldState) {
    Column {
        /* ... */
            onClick = {
                // Create a new coroutine in the event handler to show a snackbar
                scope.launch {
                    scaffoldState.snackbarHostState.showSnackbar("Something happened!")
        ) {
            Text("Press me")
Enter fullscreen mode Exit fullscreen mode



`> reference a value in an effect that shouldn't restart if the value changes

fun LandingScreen(onTimeout: () -> Unit) {

// This will always refer to the latest onTimeout function that
// LandingScreen was recomposed with
val currentOnTimeout by rememberUpdatedState(onTimeout)

// Create an effect that matches the lifecycle of LandingScreen.
// If LandingScreen recomposes, the delay shouldn't start again.
LaunchedEffect(true) {

/* Landing screen content */
Enter fullscreen mode Exit fullscreen mode


effects that require cleanup

when composable function leaves the Composition


fun HomeScreen(
lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
onStart: () -> Unit, // Send the 'started' analytics event
onStop: () -> Unit // Send the 'stopped' analytics event
) {
// Safely update the current lambdas when a new one is provided
val currentOnStart by rememberUpdatedState(onStart)
val currentOnStop by rememberUpdatedState(onStop)

// If `lifecycleOwner` changes, dispose and reset the effect
DisposableEffect(lifecycleOwner) {
    // Create an observer that triggers our remembered callbacks
    // for sending analytics events
    val observer = LifecycleEventObserver { _, event ->
        if (event == Lifecycle.Event.ON_START) {
        } else if (event == Lifecycle.Event.ON_STOP) {

    // Add the observer to the lifecycle

    // When the effect leaves the Composition, remove the observer
    onDispose {

/* Home screen content */
Enter fullscreen mode Exit fullscreen mode


i hope you enjoying it:)

Top comments (0)