DEV Community

kururu
kururu

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
1)

LaunchedEffect:

run suspend functions in the scope of a composable
`

@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.
        scaffoldState.snackbarHostState.showSnackbar(
            message = "Error message",
            actionLabel = "Retry message"
        )
    }
}

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

}`

2)
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")
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

}`

3)
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 */
Enter fullscreen mode Exit fullscreen mode

}
`

4)
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 */
Enter fullscreen mode Exit fullscreen mode

}
`

i hope you enjoying it:)

Discussion (0)