Introduction to Lifecycle Library

LifecycleLibrary 

In Android Application we usually:

  • Setup things in onStart or onCreate
  • Tear down things in onStop or onDestroy 
  • Eg. musicPlay.start() and musicPlayer.stop() 
If we forget to stop sometimes this could lead to bugs. So it would be nice if those classes which manages timers, music players, animations could be in charge of themselves. 

In 2017, Google announced Lifecycle Library with the goal of simplifying working with the activity and fragment lifecycle. 
  • Lifecycle library introduced Android Lifecycle as the actual object : this.lifecycle
  • We can query this object to check for state 
  • Lifecycle library also contains LifecycleOwner interface and LifecycleObserver interface.

LifecycleOwner 

  • A class that has a lifecycle 
  • ex. Activity and Fragment 

LifecycleObservers 

  • Allows objects to observe LifecycleOwner, such as Activity or Fragment 

Observer Pattern

   In this pattern the Observer "watch" the subject. When the state of the subject is changed it notifies the observer. IN simple words "Don't tell me what to do just tell me when your lifecycle changes, I'll handle it."

Use Case:

  • implement LifecycleObserver interface 
  • create a constructor with current lifecycle parameter 
  • setup  the observer relationship : so our class with start observing the activity lifecycle 
  • add the annotation to any method where you want to observe the lifecycle and call the method 

class CoolTimer(lifecycle: Lifecycle) : LifecycleObserver {

// number of seconds counted
var secondsCount = 0
private var handler = Handler()
private lateinit var runnable: Runnable

init {
// add this as lifecycle observer which allows for the class to
// react to changes in this activity's lifecycle state
lifecycle.addObserver(this)
}

@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun startTimer() {
runnable = Runnable {
secondsCount++
Timber.i("Timer is at: $secondsCount")
handler.postDelayed(runnable, 1000)
}
// initially start timer
handler.postDelayed(runnable, 1000)
}

@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
fun stopTimer() {
handler.removeCallbacks(runnable)
}

}










Comments

Popular Posts