Skip to content

Lifecycle Aware Components

Devrath edited this page May 1, 2021 · 3 revisions

what are life-cycle aware components

  • Life cycle aware components perform actions in response to a change in the status of another component.
  • Components can be such as activities and fragments
  • They help to produce a better organized and lightweight code that is easy to maintain.
  • Most of the app components that are defined in the Android framework have life cycles attached to them. life cycles are managed by the operating system, If the application doesn't follow the rules of the os, There may be the possibility of memory leaks

Building blocks of life-cycle aware components

The life-cycle aware components are made of 3 main parts

life-cycle life-cycle owner life-cycle observer
It is a class that holds the information of lifecycle states of components like fragments & activities This defines the owner of the lifecycle. Activity/Fragment can be called as lifecycle owner The lifecycle observer observes the state of the life cycle and here we can perform some operation

Use-cases of life-cycle aware components

  • Starting/Stopping the video buffering when the application starts and is visible, also stopping the buffering once the application is destroyed
  • Handling the location updates, when the application is in foreground /background

What order the events are triggered of lifecycle aware components along with actual life-cycle events

  • In the activity creation phase, the activity life-cycle events are triggered first followed by the observer events
  • In the activity destruction phase, the observer events are triggered followed by the life-cycle events

Demo represents how the life-cycle aware component is used

  • Here we have an activity that is playing a video using the exo-player, This exo-player is life-cycle aware
  • Activity is bound to a lifecycle aware component
  • We can observe all the logic of Exoplayer is moved into the life-cycle aware component even though the life cycle is lifecycle aware
  • This helps to organize our logic separately
  • Exoplayer Activity <->Lifecycle-aware component