androidandroid-jetpack-composeandroid-jetpackandroid-lifecycle

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.


Solution

  • 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()
        }
    
    )