Lifecycle
abstract class Lifecycle
kotlin.Any | |
↳ | androidx.lifecycle.Lifecycle |
Defines an object that has an Android Lifecycle. Fragment
and FragmentActivity
classes implement LifecycleOwner
interface which has the getLifecycle
method to access the Lifecycle. You can also implement LifecycleOwner
in your own classes.
Event#ON_CREATE
, Event#ON_START
, Event#ON_RESUME
events in this class are dispatched after the LifecycleOwner
's related method returns. Event#ON_PAUSE
, Event#ON_STOP
, Event#ON_DESTROY
events in this class are dispatched before the LifecycleOwner
's related method is called. For instance, Event#ON_START
will be dispatched after onStart
returns, Event#ON_STOP
will be dispatched before onStop
is called. This gives you certain guarantees on which state the owner is in.
If you use Java 8 Language, then observe events with DefaultLifecycleObserver
. To include it you should add "androidx.lifecycle:lifecycle-common-java8:<version>"
to your build.gradle file.
class TestObserver implements DefaultLifecycleObserver { @Override public void onCreate(LifecycleOwner owner) { // your code } }If you use Java 7 Language, Lifecycle events are observed using annotations. Once Java 8 Language becomes mainstream on Android, annotations will be deprecated, so between
DefaultLifecycleObserver
and annotations, you must always prefer DefaultLifecycleObserver
.
class TestObserver implements LifecycleObserver { @OnLifecycleEvent(ON_STOP) void onStopped() {} }
Observer methods can receive zero or one argument. If used, the first argument must be of type LifecycleOwner
. Methods annotated with Event#ON_ANY
can receive the second argument, which must be of type Event
.
class TestObserver implements LifecycleObserver { @OnLifecycleEvent(ON_CREATE) void onCreated(LifecycleOwner source) {} @OnLifecycleEvent(ON_ANY) void onAny(LifecycleOwner source, Event event) {} }These additional parameters are provided to allow you to conveniently observe multiple providers and events without tracking them manually.
Summary
Nested classes | |
---|---|
Lifecycle states. |
Public constructors | |
---|---|
<init>() Defines an object that has an Android Lifecycle. |
Public methods | |
---|---|
abstract Unit |
addObserver(@NonNull observer: LifecycleObserver) Adds a LifecycleObserver that will be notified when the LifecycleOwner changes state. |
abstract Lifecycle.State |
Returns the current state of the Lifecycle. |
abstract Unit |
removeObserver(@NonNull observer: LifecycleObserver) Removes the given observer from the observers list. |
Extension functions | ||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
From androidx.lifecycle
|