Sharing Flows & Lifecycle-Safe Collection Interview Questions
KOTLIN › Flow
Why is collecting a Flow in lifecycleScope.launch unsafe, and what should you use instead?
What a strong answer covers: lifecycleScope.launch keeps collecting while the app is in the background until the lifecycle is destroyed, wasting resources and possibly updating UI that isn't visible. Use repeatOnLifecycle(Lifecycle.State.STARTED) { flow.collect { } }, which collects when STARTED and cancels when stopped, or flowWithLifecycle. In Compose, use collectAsStateWithLifecycle.
What do stateIn and shareIn do, and why would you use them in a ViewModel?
What a strong answer covers: They turn a cold flow into a hot StateFlow or SharedFlow running in a scope, so one upstream collection is shared by all collectors instead of one per collector, and the latest value survives configuration changes. stateIn needs an initial value and gives a StateFlow; shareIn takes a replay count.
Explain the SharingStarted options. Why is WhileSubscribed(5000) such a common choice?
What a strong answer covers: Eagerly starts immediately and never stops; Lazily starts on the first subscriber and never stops; WhileSubscribed starts on the first subscriber and stops after the last one leaves, after the given timeout. 5000 ms keeps the upstream alive through a configuration change (the UI reconnects within a second) but stops it when the app has been in the background for a while, saving work like database or location updates.
What's the difference between collectAsState and collectAsStateWithLifecycle in Compose?
What a strong answer covers: collectAsState collects while the composable is in the composition, including when the app is in the background. collectAsStateWithLifecycle (lifecycle-runtime-compose) collects only while the lifecycle is at least STARTED, so with WhileSubscribed upstream work can stop in the background. It's the recommended default on Android.
A screen shows a Room flow that's also used by a background sync. After adding stateIn with Eagerly, the database query runs even when no screen is open and battery use rose. How would you reason about sharing scope and start policy?
What a strong answer covers: Eagerly in a long-lived scope (application or a singleton repository) keeps the upstream running for the life of the process. Fixes: share in viewModelScope with WhileSubscribed so it stops with the UI; keep the repository exposing cold flows and let each consumer share for its own lifetime; and if a background worker needs the data, query it directly instead of a shared hot flow. A strong answer reasons about who owns the scope and when work should stop.