Monday 3 December 2018

Android Architecture Components : Lifecycle-aware Components

Hi,
In previous post I have explained how we can use view model with live data. Now in this post I will explain , in our Activity /Fragment , how it will be LifeCycle Aware . Now first the question is what is the need of LifeCycle Awareness . So let me explain in brief on this .

The main problem of all android developers is memory leak in codebase , cause of that is an invalid state is accessed which is not synced with the lifecycle of activity/fragment of the app.
 To avoid this we have to unregister callbacks/call cleanup methods or specific functions to re-initialize at certain points in the lifecycle of Activity/Fragment.i.e onDestroy(), onResume(), onCreate(), etc.And if in any part due to hurry (to achieve deadlines ;),obviously) sometimes the cleanup part is missed or not putting in the right place in code .

 For example, if an Activity receives a callback after it’s been stopped,then it’s pretty likely that your app is going to crash due to memory leak. Unregistering the callback is right before the Activity is destroyed is what is the needed.But if this part is missed , it may cause trouble.We have to make sure to cleanup on proper events of Activity/Fragment.

 So the solution of this problem is, our activity/ fragment should be lifecycle aware.Making the components lifecycle-aware facilitates us to not to putting more code and
 checks in application to handle the states of the activity/fragment.

Now the question how , lifecycle-aware components provides us these benefits. Let's take a look:

An activity has its own lifecycle hence it is called LifeCycleOwner.
Now in lifecycle-aware components we have a class LifeCycle , this class is having Event and State as enumeration.
These are used to determine the lifecycle of LifeCycleOwner. Each event has its own state.
Event onCreate()  -> State CREATED
Event onStart()   -> State STARTED
Event onResume()  -> State RESUMED
Event onPause()  -> State PAUSED
Event onStop()  -> State STOPPED
Event onDestroy()  -> State DESTROYED
This way each event is releated to a particular state.
We also have LifeCycleObserver , which observers the LifeCycleOwner(activity/fragment) and keep track its lifecycle.
Thus the LifeCycleObserver performs action.The action performed by this LifeCycleObserver , depends on the lifecycle of LifeCycleOwner.
Thus every activity/fragment has its own LifeCycle , and on the basis of events and states of this , LifeCycleObserver performs actions.
This way LifeCycleOwner , LifeCycle and LifeCycleObserver are connected.

Now let's move to the coding part :

->Add dependency in build.gradle(app) :

implementation "android.arch.lifecycle:runtime:1.1.1"
implementation "android.arch.lifecycle:extensions:1.1.1"
annotationProcessor "android.arch.lifecycle:compiler:1.1.1"


-> Now create a java class named : LifeCycleDemoObserver.java :

import android.arch.lifecycle.Lifecycle;
import android.arch.lifecycle.LifecycleObserver;
import android.arch.lifecycle.OnLifecycleEvent;
import android.util.Log;

public class LifeCycleDemoObserver implements LifecycleObserver {

private String TAG = this.getClass().getName();

@OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
public void OnCreateObserver(){
Log.d(TAG,"On Create Observer");
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
public void OnStartObserver(){
Log.d(TAG,"On Start Observer");
}

@OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
public void OnResumeObserver(){
Log.d(TAG,"On Resume Observer");
}

@OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
public void OnPauseObserver(){
Log.d(TAG,"On Pause Observer");
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
public void OnStopObserver(){
Log.d(TAG,"On Stop Observer");
}

@OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void OnDestroyObserver(){
Log.d(TAG,"On Destroy Observer");
}
}


Here I am adding the log for all events of activity lifecycle.
Now we will add this observer in onCreate method of Activity class.
Let's take a look on activity class :

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;

import com.development.R;

public class LifeCycleDemoActivity extends AppCompatActivity {

private String TAG = this.getClass().getName();

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.life_cycle_layout);
Log.d(TAG, "Activity OnCreate");

getLifecycle().addObserver(new LifeCycleDemoObserver());
}


@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "Activity onPause");
}
 
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "Activity onResume");
}

@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "Activity onStart");
}

@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "Activity onStop");
}

@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "Activity onDestroy");
}
}


Here I have also added logs for all the events in activity . Now on running the program, we can see that all the events of observer class will call after activity log events ,and when we change the configuration , observer method will call first. I have added the log screenshot for better understanding.
















Here in above screenshot we can see that after rotation the onPause() and onStop() methods of observer class had been called first then after activity class event method had been called. In this way Lifecycle-Aware-Components take place. That's it .In next tutorial I will share a demo for Room DB .Till then happy coding. :) 


No comments:

Post a Comment

Advanced Kotlin Coroutines : Introduction

 Hi,  Today I am unwraping the topic in Kotin world i.e. Coroutine . If you want to get started with Kotlin coroutine and ease your daily de...