Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android handle lifecycle event on Jetpack Compose Screen

In Jetpack Compose all screen are composable function. Fragments are not used in Jetpack Compose.

How we can handle lifecycle events with Jetpack Compose? If we use Fragment we can handle lifecycle event (onStart/onPause/onResume/onStop). Those are useful for difference scenario like releasing resource, stop observing changes etc.

In Jetpack Compose if i need to handle those event how can i do that in Composable Screen?

Please help me with some idea or resource so that i can understand this.

Thanks in advance.

like image 267
Abu Yousuf Avatar asked Mar 21 '26 07:03

Abu Yousuf


2 Answers

You can get LifecycleOwner val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current

and register LifecycleEventObserver using DisposableEffect and remove this observer on onDispose function of DisposableEffect.

You can also use rememberUpdatedState if the functions you pass might change during recompositions.

I add a sample

@Composable
private fun DisposableEffectWithLifeCycle(
    onResume: () -> Unit,
    onPause: () -> Unit,
) {

    val context = LocalContext.current

    // Safely update the current lambdas when a new one is provided
    val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current

    Toast.makeText(
        context,
        "DisposableEffectWithLifeCycle composition ENTER",
        Toast.LENGTH_SHORT
    ).show()

    val currentOnResume by rememberUpdatedState(onResume)
    val currentOnPause by rememberUpdatedState(onPause)

    // If `lifecycleOwner` changes, dispose and reset the effect
    DisposableEffect(lifecycleOwner) {
        // Create an observer that triggers our remembered callbacks
        // for lifecycle events
        val observer = LifecycleEventObserver { _, event ->
            when (event) {
                Lifecycle.Event.ON_CREATE -> {
                    Toast.makeText(
                        context,
                        "DisposableEffectWithLifeCycle ON_CREATE",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                Lifecycle.Event.ON_START -> {
                    Toast.makeText(
                        context,
                        "DisposableEffectWithLifeCycle ON_START",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                Lifecycle.Event.ON_RESUME -> {
                    currentOnResume()
                }
                Lifecycle.Event.ON_PAUSE -> {
                    currentOnPause()
                }
                Lifecycle.Event.ON_STOP -> {
                    Toast.makeText(
                        context,
                        "DisposableEffectWithLifeCycle ON_STOP",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                Lifecycle.Event.ON_DESTROY -> {
                    Toast.makeText(
                        context,
                        "DisposableEffectWithLifeCycle ON_DESTROY",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                else -> {}
            }
        }

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

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

            Toast.makeText(
                context,
                "DisposableEffectWithLifeCycle composition EXIT",
                Toast.LENGTH_SHORT
            )
                .show()
        }
    }

    Column(modifier = Modifier.background(Color(0xff03A9F4))) {
        Text(
            text = "Disposable Effect with lifecycle",
            color = Color.White,
            modifier = Modifier
                .padding(8.dp)
                .fillMaxWidth()
        )
    }
}

Demonstration

val context = LocalContext.current

DisposableEffectWithLifeCycle(
    onResume = {
        Toast.makeText(
            context,
            "DisposableEffectWithLifeCycle onResume()",
            Toast.LENGTH_SHORT
        )
            .show()
    },
    onPause = {
        Toast.makeText(
            context,
            "DisposableEffectWithLifeCycle onPause()",
            Toast.LENGTH_SHORT
        )
            .show()
    }

)
like image 164
Thracian Avatar answered Mar 24 '26 12:03

Thracian


Create Function

@Composable
fun ComposableLifecycle(
    lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current,
    onEvent: (LifecycleOwner, Lifecycle.Event) -> Unit
) {

    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { source, event ->
            onEvent(source, event)
        }
        lifecycleOwner.lifecycle.addObserver(observer)

        onDispose {
            lifecycleOwner.lifecycle.removeObserver(observer)
        }
    }
}

Call this function inside the screen

 val TAG = "SecondScreen"
    ComposableLifecycle { _, event ->
        when (event) {
            Lifecycle.Event.ON_CREATE -> {
                Log.d(TAG, "onCreate")
            }
            Lifecycle.Event.ON_START -> {
                Log.d(TAG, "On Start")
            }
            Lifecycle.Event.ON_RESUME -> {
                Log.d(TAG, "On Resume")
            }
            Lifecycle.Event.ON_PAUSE -> {
                Log.d(TAG, "On Pause")
            }
            Lifecycle.Event.ON_STOP -> {
                Log.d(TAG, "On Stop")
            }
            Lifecycle.Event.ON_DESTROY -> {
                Log.d(TAG, "On Destroy")
            }
            else -> {}
        }
    }

Source - Life Cycle In Jetpack Compose

like image 39
Ebin Joy Avatar answered Mar 24 '26 13:03

Ebin Joy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!