Sharing Flows & Lifecycle-Safe Collection
KOTLIN › Flow
One upstream for many collectors, and collection that stops when the screen does.
Two problems meet at the seam between a cold flow and a screen: a cold flow re-runs its producer per collector, and a collector runs until its coroutine is cancelled. stateIn and shareIn fix the upstream half, repeatOnLifecycle and collectAsStateWithLifecycle fix the downstream half, and interviewers care most about whether you understand they are two halves of one handshake. Strong answers explain where the five second timeout comes from, why launchWhenStarted was deprecated, and why collectAsState is the same mistake in Compose form.
What this covers
- A cold flow re-runs its producer per collector; stateIn and shareIn make one shared hot upstream
- stateIn returns a StateFlow and requires an initialValue; shareIn returns a SharedFlow, which suits events
- SharingStarted: Eagerly and Lazily run until the scope dies; only WhileSubscribed reacts to subscriber count
- WhileSubscribed(5_000) outlasts a configuration change but not backgrounding, so rotation does not re-query
- replayExpirationMillis controls the cached value; stopTimeoutMillis controls the producer
- stateIn inside a function builds a new shared flow per call, so it must be a property
- launchWhenStarted suspends the collector instead of cancelling it, so the upstream never stops
- repeatOnLifecycle cancels the subscription, which is what lets WhileSubscribed stop the producer
- A backgrounded Activity does not leave composition, so collectAsState keeps collecting: use collectAsStateWithLifecycle
- In a Fragment use viewLifecycleOwner.lifecycleScope, since lifecycleScope outlives the view
Study this topic
- Sharing Flows & Lifecycle-Safe Collection explained: the guided lesson
- 16 practice quiz questions
- 13 revision flashcards
- Sharing Flows & Lifecycle-Safe Collection interview questions and answers