Customizing Life Cycles
Previously, we discussed LiveData
and how it can be observed through a LifecycleOwner
. We can use LifecycleOwners to subscribe to a LifecycleObserver
so that it will monitor when the state of an owner changes. This is useful in situations where you would want to trigger certain functions when certain life cycle callbacks are invoked; for example, requesting locations, starting/stopping videos, and monitoring connectivity changes from your activity/fragment. We can achieve this with the use of a LifecycleObserver
:
class ToastyLifecycleObserver(val onStarted: () -> Unit) : LifecycleObserver { @OnLifecycleEvent(Lifecycle.Event.ON_START) fun onStarted() { onStarted.invoke() } }
In the preceding code, we have defined a class that implements the LifecycleObserver
interface and defined a method that will be called when the life cycle goes...