Life Cycle Components

Life Cycle Components

 
 

Life Cycle Aware Components

  • Most of the code is written inside Activity LifeCycle Methods - onCreate, onResume, onPause etc.
  • Due to this, Activity has multiple responsibilities. But there are scenarios where we want to take actions based on the activity lifeCycle. For e.g.
    • Access the User's Location.
    • Playing Video.
    • Downloading Images.
 

Life Cycle Aware Components Type

  1. Owner ( Who has its Own Life cycle )
      • Activity
      • Fragment
  1. Life Cycle Observer
 

Need :

  • Observer will keep watch on Owner’s Lifecycle state
  • and it will perform some task based on its state
  • Its Helps to separate code for lifecycle methods from Owner (Activity)
  • It helps to make clean architecture
 

Example:

 

Observer.kt

package com.example.androidarchitecture import android.util.Log import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleObserver import androidx.lifecycle.OnLifecycleEvent class Observer : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_CREATE) fun onCreate() { Log.d("====", "Observer - onCreate") } @OnLifecycleEvent(Lifecycle.Event.ON_RESUME) fun onResume() { Log.d("====", "Observer - onResume") } @OnLifecycleEvent(Lifecycle.Event.ON_STOP) fun onStop() { Log.d("====", "Observer - onStop") } @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE) fun onPause() { Log.d("====", "Observer - onPause") } @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY) fun onDestroy() { Log.d("====", "Observer - onDestroy") } }
 

MainActivity.kt

package com.example.androidarchitecture import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import com.example.androidarchitecture.databinding.ActivityMainBinding class MainActivity : AppCompatActivity() { private val TAG: String = "====" private val binding: ActivityMainBinding by lazy { ActivityMainBinding.inflate(layoutInflater) } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(binding.root) // add LifeCycle Observer on Our Activity lifecycle.addObserver(Observer()) Log.d("====", "Activity onCreate") } override fun onResume() { super.onResume() Log.d(TAG, "Activity - onResume") } override fun onPause() { super.onPause() Log.d(TAG, "Activity - onPause") } override fun onStop() { super.onStop() Log.d(TAG, "Activity - onStop") } override fun onDestroy() { super.onDestroy() Log.d(TAG, "Activity - onDestroy") } }
 

Benefits:

  • so Our life cycle observer is separate from activity so we can assign this observer to multiple Activities Or Fragments without copy & pasting same task on each components.
  • when Activity lifecycle method called Observer automatically invoke method relate to that method Or has Connection with that method from observer class