With Jetpack Lifecycle, how do you build a GPS boarding-gate checker as a DefaultLifecycleObserver, and what does a late addObserver call deliver?
answer
- the component owns its start and stop
- override only the callbacks you need
- catch-up events on registration
- addObserver is a main-thread call
- @OnLifecycleEvent deprecated since 2.4.0
basics
~10 sImplement DefaultLifecycleObserver, override onStart to begin GPS checks and onStop to end them, then call lifecycle.addObserver(checker). Added late, the observer is replayed every event up to the current state, in order.
solid answer
~30 s`DefaultLifecycleObserver` has empty default methods, `onCreate(owner)` through `onDestroy(owner)`, so the gate checker overrides only `onStart` and `onStop` and the screen just calls `lifecycle.addObserver(checker)` in `onCreate`. `addObserver` brings the observer to the owner's current state: added while `RESUMED`, it immediately receives `ON_CREATE`, `ON_START` and `ON_RESUME`. Adding the same instance twice is ignored, and `removeObserver` stops delivery. The call belongs on the main thread; a `LifecycleRegistry` made with its public constructor throws `IllegalStateException` otherwise. `LifecycleEventObserver` is the one-method alternative, Lifecycle 2.11 adds a lambda `Lifecycle.addObserver { source, event -> }`, and the `@OnLifecycleEvent` annotation is deprecated.
code
kotlin · 13 linesimport androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.LifecycleOwner
class BoardingGateCheck(
private val startGps: () -> Unit,
private val stopGps: () -> Unit,
) : DefaultLifecycleObserver {
override fun onStart(owner: LifecycleOwner) = startGps()
override fun onStop(owner: LifecycleOwner) = stopGps()
}
// In the boarding screen's onCreate:
// lifecycle.addObserver(BoardingGateCheck(::startGps, ::stopGps))go deeper
Recall that DefaultLifecycleObserver has empty default methods, so you override only onStart and onStop, and register with lifecycle.addObserver.
Explain the catch-up replay on registration, the main-thread rule, duplicate-add being ignored, and the order when a class implements both observer interfaces.
Spot leaks from observers registered on a longer-lived lifecycle, and pick STARTED versus RESUMED boundaries deliberately for hardware like GPS.
Push lifecycle handling into components the team can test with a LifecycleRegistry, instead of start and stop calls scattered through screen callbacks.
## Why a component observes the lifecycle itself A **lifecycle-aware component** keeps its own start and stop logic instead of asking every screen to call it from callbacks. The GPS boarding-gate checker on a ferry app should only poll position while its screen is visible. Written as an observer, the screen does one thing: register it. The checker decides what to do on each event. The Jetpack Lifecycle library offers two observer interfaces, both extending the marker interface `LifecycleObserver` (which the library says not to implement directly): | Interface | Shape | Fits when | |---|---|---| | `DefaultLifecycleObserver` | six methods with empty defaults: `onCreate`, `onStart`, `onResume`, `onPause`, `onStop`, `onDestroy`, each taking the `owner` | the component reacts to a few named events | | `LifecycleEventObserver` | a `fun interface` with `onStateChanged(source, event)` | one handler that switches on the event | If a class implements both, the `DefaultLifecycleObserver` method runs first, followed by `onStateChanged`. ## Building the checker ```kotlin class BoardingGateCheck( private val startGps: () -> Unit, private val stopGps: () -> Unit, ) : DefaultLifecycleObserver { override fun onStart(owner: LifecycleOwner) = startGps() override fun onStop(owner: LifecycleOwner) = stopGps() } // in the boarding screen's onCreate: lifecycle.addObserver(BoardingGateCheck(::startGps, ::stopGps)) ``` Pairing `onStart` with `onStop` matches the visible window. `onResume` and `onPause` would also stop the check whenever the screen loses focus while still visible, which is rarely what a location check wants. ## What addObserver does when it is called late The `Lifecycle.addObserver` contract says the observer **is brought to the current state** of the owner. In practice: 1. The observer starts at `INITIALIZED` (or `DESTROYED` if the lifecycle already is). 2. The registry dispatches each upward event in turn until the observer reaches the owner's state. 3. Added while the owner is `RESUMED`, the observer receives `ON_CREATE`, then `ON_START`, then `ON_RESUME`, synchronously. 4. Added after the owner is `DESTROYED`, it receives nothing. This replay is why a checker registered in `onResume` by mistake still starts GPS: it is told `ON_START` immediately. Other properties worth knowing: - Adding an instance that is already registered is a no-op, so it is not called twice. - `removeObserver` stops delivery; if called mid-dispatch, an observer that has not yet received that event will not receive it. - `addObserver`, `removeObserver` and `currentState` are main-thread APIs. A `LifecycleRegistry` created through its public constructor checks this and throws `IllegalStateException` ("Method addObserver must be called on the main thread"); `LifecycleRegistry.createUnsafe` skips the check, for owners synchronised externally or for plain JVM tests. ## Lifetime and leaks The registry holds its owner through a weak reference but holds **observers strongly**. An observer registered on the owner's own lifecycle goes away with it. The leak appears when a short-lived object registers on a longer-lived lifecycle, such as an Activity adding an observer that captures itself to the process-wide owner and never removing it. In a Fragment, the observer usually belongs on the view's lifecycle rather than the Fragment's, a choice covered with Fragment view lifecycles. ## Older and newer styles - **`@OnLifecycleEvent`** on methods of a plain `LifecycleObserver` was deprecated in Lifecycle 2.4.0 because it needed reflection or generated code; the deprecation points to `DefaultLifecycleObserver` or `LifecycleEventObserver`. - **Lifecycle 2.11** added a lambda-based extension, `Lifecycle.addObserver { source, event -> }`, which wraps the lambda in a `LifecycleEventObserver`, registers it, and returns the observer so it can be passed to `removeObserver` later. ```kotlin val observer = lifecycle.addObserver { _, event -> if (event == Lifecycle.Event.ON_START) startGps() if (event == Lifecycle.Event.ON_STOP) stopGps() } // later: lifecycle.removeObserver(observer) ``` ## Review checklist for an observer 1. Is it registered **once**, from `onCreate`, on the lifecycle whose lifetime matches the work? 2. Are start and stop **paired at the same level** (`onStart` with `onStop`, `onResume` with `onPause`), so every start has a matching stop? 3. Does it hold a reference to anything shorter-lived than the lifecycle it is registered on? 4. If it is removed early, is `removeObserver` called with the **same instance** that was added, or with the value returned by the lambda extension? 5. Does it avoid heavy work in callbacks that run on the main thread, handing that work to a coroutine or another component instead? An observer that passes these five checks behaves the same whether it is attached to an Activity, a Fragment's view, a navigation entry or the process-wide owner, which is the whole point of writing the logic once in a component. Either way, the component stays testable: a test can drive it with a `LifecycleRegistry` and `handleLifecycleEvent` without an Activity.
- The checker is registered in onResume by mistake. Does GPS still start, and what else goes wrong?Yes. `addObserver` replays `ON_CREATE`, `ON_START` and `ON_RESUME`, so `onStart` runs at once. But every later `onResume` calls `addObserver` with a new instance, so several checkers accumulate on the same lifecycle; registering the same instance again would be ignored. Register once, in `onCreate`.
- How do you unit-test the checker without an Activity?Create a `LifecycleOwner` backed by a `LifecycleRegistry` (or `LifecycleRegistry.createUnsafe` off the main thread in a plain JVM test), add the checker, then call `handleLifecycleEvent(Lifecycle.Event.ON_START)` and `ON_STOP` and assert the start and stop lambdas ran.
- An observer added late only sees events that happen afterwards
- DefaultLifecycleObserver forces you to implement all six methods
- Adding the same observer twice makes it receive every event twice
- @OnLifecycleEvent is the recommended way to observe
- Observers can be added from any background thread safely
Assumes Lifecycle 2.11; the lambda Lifecycle.addObserver extension is new in 2.11.0, and @OnLifecycleEvent is deprecated since 2.4.0.