Jetpack Compose Lifecycle
Tags: jetpackcompose, lifecycle, android, kotlin
Published: 2022-02-24 12:03:52

  **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.](https://developer.android.com/jetpack/compose/lifecycle)



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/uc0qj1bvle0rd7951vzo.png)




so here we  treat something called **Composition** :)


so composable function has three lifecycle:

     -  enter composition
     -  recomposition n times
     -   leave composition

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


[> Recomposition is typically triggered by a change to a State<T> object. Compose tracks these and runs all composables in the Composition that read that particular State<T>, and any composables that they call that cannot be skipped.](https://developer.android.com/jetpack/compose/lifecycle)


  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.](https://developer.android.com/jetpack/compose/side-effects)


[> An effect is a composable function that doesn't emit UI and causes side effects to run when a composition completes.](https://developer.android.com/jetpack/compose/side-effects)

   


there are many side-Effect function in compose 
1)  
[**LaunchedEffect**](https://developer.android.com/jetpack/compose/side-effects#launchedeffect):

>  run suspend functions in the scope of a composable
`


@Composable
fun MyScreen(
    state: UiState<List<Movie>>,
    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.
            scaffoldState.snackbarHostState.showSnackbar(
                message = "Error message",
                actionLabel = "Retry message"
            )
        }
    }

    Scaffold(scaffoldState = scaffoldState) {
        /* ... */
    }
}`



2) 
**[rememberCoroutineScope](https://developer.android.com/jetpack/compose/side-effects#remembercoroutinescope)**:
 

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


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

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

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



3)
**[rememberUpdatedState](https://developer.android.com/jetpack/compose/side-effects#rememberupdatedstate)**: 

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




@Composable
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) {
        delay(SplashWaitTimeMillis)
        currentOnTimeout()
    }

    /* Landing screen content */
}
`




4)
**[DisposableEffect](https://developer.android.com/jetpack/compose/side-effects#disposableeffect)**:
 effects that require cleanup

  when composable function leaves the **Composition**

`


@Composable
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) {
                currentOnStart()
            } else if (event == Lifecycle.Event.ON_STOP) {
                currentOnStop()
            }
        }

        // Add the observer to the lifecycle
        lifecycleOwner.lifecycle.addObserver(observer)

        // When the effect leaves the Composition, remove the observer
        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }

    /* Home screen content */
}
`




i hope you enjoying it:)