Life Cycle In Jetpack Compose

Life Cycle In Jetpack Compose

In Android, the life cycle refers to the series of states that an application component, such as an Activity or Fragment, goes through during its lifespan. Each component has a set of life cycle methods that are called by the Android system at different stages, allowing developers to execute code and manage the behavior of their app. Understanding the life cycle is crucial for properly managing resources, handling user interactions, and maintaining a smooth user experience.

Android lifecycle

  1. Created: The screen is created, but it is not yet visible to the user. The onCreate() method is called during this stage, where you typically initialize variables, set up the UI, and perform other one-time setup tasks.
  2. Started: The screen becomes visible to the user, but it may not be in the foreground and may be partially obscured by other screens or system windows. The onStart() method is called, where you can start animations, register broadcast receivers, or initialize components that should be active when the activity is visible.
  3. Resumed: The screen is in the foreground and has user focus. It is now interacting with the user. The onResumed() method is called, where you can start or resume animations, acquire system resources, and update the UI.
  4. Paused: The screen loses focus but remains visible in the background. This can happen, for example, when another screen is launched in front of it or when the device goes to sleep. The onPause() method is called, allowing you to pause ongoing tasks, release system resources, and save persistent data.
  5. Stopped: The screen is no longer visible to the user. This can occur when the activity is either completely hidden by another activity or the user navigates away from it. The onStop() method is called, giving you an opportunity to release resources that are no longer needed and perform cleanup tasks.
  6. Destroyed: The screen is being destroyed and removed from memory. This happens when the activity is finished, or the system needs to reclaim resources. The onDestroy() method is called, allowing you to release any remaining resources, unregister listeners, and perform final cleanup.

How to implement ?

There are two ways.

#First way inside the screen.

Observe the lifecycle events of a given LifecycleOwner and perform actions based on those events.

  1. Create fun

@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)
        }
    }
}        

2. Call this fun inside screen

 val TAG = "MyScreen"
    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 -> {}
        }
    }        

#Second way include it inside view model.

observe the lifecycle events of a given Lifecycle object in view model

  1. Create extension fun

@Composable
fun <viewModel : LifecycleObserver> viewModel.observeLifecycleEvents(lifecycle: Lifecycle) {
    DisposableEffect(lifecycle) {
            lifecycle.addObserver(this@observeLifecycleEvents)
        onDispose {
            lifecycle.removeObserver(this@observeLifecycleEvents)
        }
    }
}        

2. Implement DefaultLifecycleObserver in viewModel class

class MyViewModel: ViewModel(), DefaultLifecycleObserver {

    private val TAG = "MyViewModel"
    override fun onCreate(owner: LifecycleOwner) {
        super.onCreate(owner)
        Log.d(TAG, "onCreate")
    }

    override fun onResume(owner: LifecycleOwner) {
        super.onResume(owner)
        Log.d(TAG, "onResume")
    }

    override fun onStart(owner: LifecycleOwner) {
        super.onStart(owner)
        Log.d(TAG, "onStart")
    }

    override fun onPause(owner: LifecycleOwner) {
        super.onPause(owner)
        Log.d(TAG, "onPause")
    }

    override fun onStop(owner: LifecycleOwner) {
        super.onStop(owner)
        Log.d(TAG, "onStop")
    }

    override fun onDestroy(owner: LifecycleOwner) {
        super.onDestroy(owner)
        Log.d(TAG, "onDestroy")
    }
}        

3. Invoke the observeLifecycleEvents function on a viewModel instance and passing in the Lifecycle object obtained from the current LocalLifecycleOwner.

viewModel.observeLifecycleEvents(LocalLifecycleOwner.current.lifecycle)        

Finally, It’s important to handle the life cycle methods correctly to ensure the proper functioning and responsiveness of your app. Managing resources, saving and restoring state, and handling configuration changes are common tasks that need to be considered when working with the Android life cycle.

Follow: Arun Aditya

#Jetpack Compose #Lifecycle #Android Lifecycle #Lifecycle Methods #LInkedin Learning


Very informative????

赞
回复
Justin P. Jose

Android Developer @ GreedyGame

4 个月

Great tip! Understanding the lifecycle is key to building smooth and efficient apps. ??

要查看或添加评论,请登录

Arun Aditya的更多文章

社区洞察

其他会员也浏览了