Lifecycle, LiveData & repeatOnLifecycle Interview Questions

ARCHITECTURE › Components

What is LiveData, and what does lifecycle-aware mean?

What a strong answer covers: LiveData is an observable data holder that knows its observers' lifecycle: it only delivers updates to observers in the STARTED or RESUMED state, and removes them automatically when their lifecycle is destroyed. So updates never reach a stopped screen and observers don't leak.

What is the difference between setValue and postValue?

What a strong answer covers: setValue must be called on the main thread and updates immediately. postValue can be called from any thread and posts a task to the main thread; if called several times before that task runs, only the last value is delivered, so intermediate values are lost.

What is repeatOnLifecycle, and why was it introduced?

What a strong answer covers: repeatOnLifecycle(Lifecycle.State.STARTED) { } launches the block each time the lifecycle reaches STARTED and cancels it when it falls below. It was introduced because launchWhenStarted only paused the coroutine, leaving upstream flows active in the background, while lifecycleScope.launch collected forever. It gives Flow the same safety LiveData had.

How do you create a component that reacts to lifecycle events without the Activity calling it manually?

What a strong answer covers: Implement DefaultLifecycleObserver with onStart, onStop and so on, and register it with lifecycle.addObserver(observer). The component then manages itself, like a location manager that starts and stops with the screen. ProcessLifecycleOwner gives you app foreground and background events. In Compose, use LifecycleEventEffect or DisposableEffect with an observer.

When would you still choose LiveData over StateFlow today, and what are the issues with LiveData in a modern codebase?

What a strong answer covers: It's reasonable in existing View-based or Java code, or with data binding. Issues: it's Android-only so ViewModels aren't pure Kotlin and can't be shared with KMP; limited operators (Transformations only); it's nullable and initial values are optional; it's main-thread oriented; and postValue drops values. StateFlow plus collectAsStateWithLifecycle or repeatOnLifecycle covers the same safety with more power.

Back to Lifecycle, LiveData & repeatOnLifecycle