skip to content

Jetpack Architecture Components

ViewModel and the Lifecycle library: screen state that outlives a rotation, and coroutines that stop with the screen. Asked in nearly every Android interview, for Views and Compose alike.

on this pageshow

explore

questions

11

In Jetpack Lifecycle, what are the Lifecycle.State and Lifecycle.Event values, and how does each event move an owner between states?

level: juniorimportance: must knowfreq 62%

answer

  1. five states, six real events
  2. states are nodes, events are edges
  3. no PAUSED or STOPPED state
  4. ON_PAUSE lands in STARTED, ON_STOP in CREATED
  5. isAtLeast compares enum order

basics

~10 s

Lifecycle.State has five values, DESTROYED, INITIALIZED, CREATED, STARTED and RESUMED; Lifecycle.Event has ON_CREATE through ON_DESTROY plus ON_ANY. Each event moves the owner one step: ON_PAUSE back to STARTED, ON_STOP back to CREATED.

solid answer

~30 s

`Lifecycle.State` is an ordered enum: `DESTROYED`, `INITIALIZED`, `CREATED`, `STARTED`, `RESUMED`, and `isAtLeast()` compares that order. `Lifecycle.Event` holds the edges: `ON_CREATE`, `ON_START` and `ON_RESUME` move up, `ON_PAUSE`, `ON_STOP` and `ON_DESTROY` move down, and `ON_ANY` only matches every event. There is no paused or stopped state: `ON_PAUSE` returns the owner to `STARTED` and `ON_STOP` to `CREATED`, which `Event.targetState` reports. Upward events are dispatched after the owner's matching method returns and downward ones before it is called, so an observer always sees a consistent state. For a departures board, "visible" means `currentState.isAtLeast(Lifecycle.State.STARTED)`.

code

kotlin · 13 lines
kotlin
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner

fun LifecycleOwner.isBoardVisible(): Boolean =
    lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)

fun describe(event: Lifecycle.Event): String =
    "$event -> ${event.targetState}"

// describe(Lifecycle.Event.ON_PAUSE) == "ON_PAUSE -> STARTED"
// describe(Lifecycle.Event.ON_STOP)  == "ON_STOP -> CREATED"
// Lifecycle.Event.upTo(Lifecycle.State.STARTED)    == ON_START
// Lifecycle.Event.downFrom(Lifecycle.State.STARTED) == ON_STOP

go deeper

for a junior

Recite the five states in order and the six events, and say which state each event lands in, especially that ON_PAUSE and ON_STOP fall back to STARTED and CREATED.

for a middle

Explain isAtLeast as an enum comparison, the after-return versus before-call dispatch rule, and why ON_ANY has no target state.

for a senior

Use the state model to pick thresholds: STARTED for visible work, RESUMED only for focus-bound work, and show how upTo and downFrom drive start and stop.

for a principal

Set the team convention that UI work is gated on at least STARTED, read through the library rather than hand-rolled booleans mirrored from callbacks.

## Two enums: nodes and edges The Jetpack Lifecycle library models a screen, or any other **`LifecycleOwner`**, as a small state machine. The library's own description is that **states are the nodes of a graph and events are the edges between them**. Both live inside the abstract class `Lifecycle`, which an owner exposes through its `lifecycle` property. - **`Lifecycle.State`**: `DESTROYED`, `INITIALIZED`, `CREATED`, `STARTED`, `RESUMED`, declared in that order. - **`Lifecycle.Event`**: `ON_CREATE`, `ON_START`, `ON_RESUME`, `ON_PAUSE`, `ON_STOP`, `ON_DESTROY`, and the special `ON_ANY`. Because `DESTROYED` is declared first, it is the *lowest* state, and `State.isAtLeast(state)` is simply an enum comparison (`compareTo(state) >= 0`). That ordering is what lets code ask "is the screen at least started?" with one call. ## How each event moves the owner Every real event has a **target state**, exposed as `Event.targetState`: | Event | Direction | State after it | |---|---|---| | `ON_CREATE` | up | `CREATED` | | `ON_START` | up | `STARTED` | | `ON_RESUME` | up | `RESUMED` | | `ON_PAUSE` | down | `STARTED` | | `ON_STOP` | down | `CREATED` | | `ON_DESTROY` | down | `DESTROYED` | The table shows the point most people miss: **there is no PAUSED and no STOPPED state**. Going down, the owner revisits the states it passed on the way up. After `ON_PAUSE` it is `STARTED` again, after `ON_STOP` it is `CREATED` again. Reading `ON_ANY.targetState` throws `IllegalArgumentException`, because `ON_ANY` is a wildcard for matching, not a transition. The companion helpers make the graph explicit and are what the library's own coroutine helpers use: 1. `Event.upTo(state)` gives the event that enters a state from below (`upTo(STARTED)` is `ON_START`). 2. `Event.downFrom(state)` gives the event that leaves it downward (`downFrom(STARTED)` is `ON_STOP`). 3. `Event.upFrom` and `Event.downTo` answer the other two directions, and each returns `null` where no such edge exists. ## When events are dispatched relative to the owner `Lifecycle` documents an ordering guarantee that matters when an observer touches UI: - `ON_CREATE`, `ON_START` and `ON_RESUME` are dispatched **after** the owner's related method returns. - `ON_PAUSE`, `ON_STOP` and `ON_DESTROY` are dispatched **before** the owner's related method is called. So the state an observer reads is never ahead of the owner on the way up or behind it on the way down. Once `DESTROYED` is reached, the lifecycle dispatches no more events. The exact sequence of Activity callbacks on rotation, Home and Back belongs to the lesson on Activity and Fragment lifecycles; this library only maps those moments to its own states and events. ## Reading the state in code Three read paths on `Lifecycle` cover most needs: - `currentState`, a property annotated for main-thread reads, for a one-off check. - `currentStateFlow`, a `StateFlow<Lifecycle.State>` whose `value` follows the state, for code that reacts to changes. - `addObserver()`, for components that must run code on each event. For the ferry-departures board, the honest definition of "the board is on screen" is `lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED)`, not `== RESUMED`: a visible screen that lost focus has received `ON_PAUSE` and is `STARTED`, yet it is still visible. ```kotlin fun LifecycleOwner.isBoardVisible(): Boolean = lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) ``` ## Common mistakes in interviews and reviews - **Inventing paused and stopped states.** Code that tracks `isPaused` by hand usually exists because someone expected a `PAUSED` value. The library answers the same question with `currentState` and `isAtLeast`. - **Mirroring callbacks into booleans.** A `visible` flag set in one callback and cleared in another drifts as soon as a callback is missed; reading the lifecycle is always current. - **Treating `ON_ANY` as a state.** It exists so an observer can match every event; it never changes the state and has no target. - **Assuming `DESTROYED` is reversible.** After `DESTROYED` the lifecycle dispatches nothing more, and a new screen instance gets a new `Lifecycle` starting at `INITIALIZED`. - **Comparing with `==` where a threshold is meant.** `currentState == STARTED` is false while the screen is `RESUMED`, which is almost never what visibility checks intend. ## Why the model is shaped this way Because states are ordered and events are edges, a component can say "run while at least `STARTED`" and the library can derive when to start (`upTo`) and when to stop (`downFrom`). That is exactly how `repeatOnLifecycle` and `flowWithLifecycle` decide when to launch and cancel work, and why passing `INITIALIZED` to them is rejected: there is no event that enters `INITIALIZED`.

  • Why does a departures board check isAtLeast(STARTED) instead of currentState == RESUMED?
    `RESUMED` means the screen is in front and has focus. A screen that loses focus but stays visible receives `ON_PAUSE` and drops back to `STARTED`, so an equality check on `RESUMED` would treat a visible board as hidden. `isAtLeast(Lifecycle.State.STARTED)` is true for both `STARTED` and `RESUMED`, which matches "on screen".
  • How does code react to state changes without registering an observer by hand?
    `Lifecycle.currentStateFlow` is a `StateFlow<Lifecycle.State>` whose `value` is the current state, so a coroutine can collect it or `first { it.isAtLeast(...) }` on it. For one-off reads `currentState` is enough.

  • Lifecycle.State has PAUSED and STOPPED values
  • After ON_STOP the owner is in DESTROYED
  • INITIALIZED is the lowest state, below DESTROYED
  • ON_ANY is a real transition with its own target state
  • Visible on screen means currentState == RESUMED
open as a page

In a Jetpack ViewModel, why does screen state survive a rotation, and when does the ViewModelStore finally clear the ViewModel?

level: juniorimportance: must knowfreq 82%

basics

~20 s

A ViewModel lives in its owner's ViewModelStore, which survives a configuration change, so the recreated Activity gets the same instance back. The store clears it, calling onCleared, only when the owner ends for good, such as a finished Activity or a popped navigation entry.

open as a page

In Jetpack Lifecycle, why is launchWhenStarted deprecated in favour of repeatOnLifecycle(Lifecycle.State.STARTED), and what does each do when the screen stops?

level: middleimportance: must knowfreq 72%

basics

~20 s

launchWhenStarted only suspends its block on a pausing dispatcher when the screen stops, so a flow's producer keeps running and wastes resources. repeatOnLifecycle(STARTED) cancels the block on ON_STOP and relaunches it on ON_START; launchWhenX is deprecated since Lifecycle 2.6.0.

open as a page

In a Jetpack ViewModel, how does SavedStateHandle keep a half-filled car-rental booking form across process death, and what are its limits?

level: middleimportance: must knowfreq 74%

basics

~20 s

SavedStateHandle is a key-value map the ViewModel receives in its constructor; it is written into the owner's saved state when the Activity stops and restored after process death. It holds only Bundle-compatible values, and loses them when the user removes the task.

open as a page

With Jetpack Lifecycle, how do you build a GPS boarding-gate checker as a DefaultLifecycleObserver, and what does a late addObserver call deliver?

level: middleimportance: should knowfreq 45%

basics

~10 s

Implement 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.

open as a page

In Jetpack Lifecycle, how do you write a ViewModelProvider.Factory with CreationExtras for a ViewModel needing a repository, a branch id and a SavedStateHandle?

level: middleimportance: should knowfreq 40%

basics

~20 s

Define viewModelFactory { initializer { } } whose lambda reads the Application from APPLICATION_KEY, the branch id from a custom CreationExtras.Key and calls createSavedStateHandle(). Pass the branch id in extras built on the owner's default extras.

open as a page

A ferry-departures Activity on Jetpack Lifecycle calls lifecycleScope.launch { departures.collect { } } in onStart; why does it keep polling in the background and show duplicate updates, and what fixes it?

level: seniorimportance: should knowfreq 55%

basics

~10 s

lifecycleScope is cancelled only at DESTROYED, so the collector outlives ON_STOP, and every onStart adds another. Launch once in onCreate and wrap the collection in repeatOnLifecycle(Lifecycle.State.STARTED), with one launch per flow.

open as a page

With Jetpack's ProcessLifecycleOwner, how do you start an analytics session each time the app comes to the foreground, and why does its ON_STOP arrive late?

level: seniorimportance: should knowfreq 35%

basics

~20 s

Register an observer on ProcessLifecycleOwner.get().lifecycle in Application.onCreate and start the session in onStart. Its ON_PAUSE and ON_STOP are delayed after the last activity pauses and stops, so an Activity recreated for a configuration change produces no events.

open as a page

In a Jetpack ViewModel, why does a viewModelScope.launch inside onCleared never run, and in what order are closeables, the scope and onCleared torn down?

level: seniorimportance: should knowfreq 46%

basics

~20 s

viewModelScope is registered as a keyed AutoCloseable, and clearing closes keyed resources first, then constructor and keyless ones, and only then calls onCleared. By then the scope is cancelled, so a coroutine launched there is cancelled before its body runs.

open as a page

With Jetpack ViewModel in a three-step car-rental booking flow, each step's viewModel() call gets a fresh instance and the extras step sees an empty form; why, and which ViewModelStoreOwner should own it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

Compose's viewModel() uses the nearest ViewModelStoreOwner, and in a navigation host that is each step's own back-stack entry, so each step gets its own instance. Scope the shared ViewModel to an owner spanning exactly the flow, such as the flow's parent graph entry.

open as a page

For Jetpack ViewModel and SavedStateHandle, what team rule would you set for which state is saved in the handle and which is reloaded after process death?

level: principalimportance: should knowfreq 33%

basics

~20 s

Save in SavedStateHandle only small user input and the ids needed to rebuild the screen; reload everything derivable from those ids through the data layer. Persist to disk whatever must survive the user closing the task, and test the rule with simulated process death.

open as a page