Lifecycle, LiveData & repeatOnLifecycle Flashcards

ARCHITECTURE › Components

When does LiveData consider an observer 'active' and deliver updates?
Only when its LifecycleOwner is STARTED or RESUMED. Inactive observers are skipped, and observers are auto-removed when the owner reaches DESTROYED.
What is the difference between setValue() and postValue() on MutableLiveData?
setValue() must be called on the main thread and updates synchronously; postValue() can be called from any thread and schedules the update onto the main thread. Rapid postValue calls can be coalesced, so only the last value may be delivered.
When would you use MediatorLiveData instead of map or switchMap?
When you need to merge multiple LiveData sources into one. You addSource() each input and react to whichever emits, e.g. combining cache and network streams into a single observable.
Explain map vs switchMap on LiveData.
map applies a synchronous transform to each value. switchMap returns a new LiveData per input value and swaps the active source, automatically removing the previous one. Use switchMap for dependent async lookups (e.g. userId -> getUser(userId)).
What does Lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) do?
It is a suspend function that launches its block in a new coroutine each time the lifecycle reaches the target state and cancels it when the lifecycle drops below that state, repeating until DESTROYED. It is the safe way to collect a Flow in the View system.
Why are launchWhenStarted / launchWhenCreated deprecated in favor of repeatOnLifecycle?
launchWhenX only suspends the coroutine when below the target state but never cancels it, so upstream Flow producers keep running and waste resources in the background. repeatOnLifecycle actually cancels collection when stopped and restarts it when started again.
In the View system, where do you call lifecycleScope.launch { repeatOnLifecycle(...) { ... } } and why?
In onCreate(). repeatOnLifecycle internally handles starting at STARTED and cancelling at STOPPED, so calling it once in onCreate avoids the manual start/stop wiring you would need in onStart/onStop.
What are the five Lifecycle.State values and which interface should observe them today?
INITIALIZED, CREATED, STARTED, RESUMED, DESTROYED. Implement DefaultLifecycleObserver (with onStart/onResume/etc.) instead of the deprecated @OnLifecycleEvent annotations or raw LifecycleObserver.
Why prefer Flow over LiveData in the data/repository layer, and how do you bridge to UI?
Flow supports threading, operators, and composition; LiveData transforms run on the main thread and are awkward to combine. Keep Flow in the data layer and expose it from the ViewModel via StateFlow or asLiveData(), so the UI stays lifecycle-aware.

Back to Lifecycle, LiveData & repeatOnLifecycle