Lifecycle Aware Components

Lifecycles

Lifecycle is the biggest developer pain point. Lifecycle is hard. Lifecycle aware observable things that can do something base on the lifecycle. Your application must respect components lifecycles. Not doing so may trigger memory leaks or even application crashes.

Imagine we have an activity that shows the device location on the screen.

What if myLocationManager.addLocationListener() will be called after myLocationManager.removeLocationListenrer() called, basically keeping the connection forever.

Lifecycle aware component

Components

New lifecycle-aware components provide constructs to tie core components(activity, fragment) of your applications to lifecycle events, removing explicit dependency paths.It can take care of itself. You can just initialize it and forget about it.

Lifecycle

Lifecycle is a class that holds the information about the lifecycle state of a component (like an activity or a fragment) and allows other objects to observe this state.

Lifecycle Components

LifecycleOwner

This is a thing with a lifecycle, it is your activity or your fragment or maybe you have your own UI framework.There as a lifecycle Owner.

Now we make our activity extend the LifecycleActivity class

LifecycleObserver

LifecycleObserver is the thing that cares about the Lifecycle.Like the LocationManager. It cares about the lifecycle, it wants to stop itself if the lifecycle is not active.

A class can monitor the component’s lifecycle status by adding annotations to its methods.

Now, we initialize MyLocationManager with our Lifecycle(MainActivity) on onCreate and stop worrying about it afterwards. This allows MyLocationManager class to be self sufficient, meaning that it can do its own cleanup when necessary.

Passes the LifecycleOwner as the first argument.

Implementing LifecycleOwner in Custom Activities and Fragments

Any custom fragment or activity can be turned into a LifecycleOwner by implementing the built-in LifecycleRegistryOwner interface

Adding Lifecycle to your Project

Architecture Components are available from Google’s Maven repository. To use them, follow these steps:

Add the Google Maven repository

To add it to your project, open the build.gradle file for your project and add the highlighted line as shown below:

Add Architecture Components

Open the build.gradle file for your app or module and add the artifacts that you need as dependencies:

 

Download this project from GitHub.

Related Post

ViewModel

Room Persistence Library

LiveData

Fragment Tricks

ConstraintLayout 1.1.x

 

Leave a Reply

Your email address will not be published. Required fields are marked *