🐦 Kotlin
Advanced
What is SharingStarted in Kotlin Flow?
Answer
SharingStarted is a strategy that controls when a shared Flow (via stateIn() or shareIn()) starts and stops collecting from its upstream Flow. SharingStarted.Eagerly starts collecting immediately and never stops. SharingStarted.Lazily starts when the first collector appears and never stops. SharingStarted.WhileSubscribed(5000) starts on the first collector and stops 5 seconds after the last collector disappears — this is the recommended choice for Android ViewModels because it cancels the upstream (and API calls) when the UI goes to the background, saving resources, while the 5-second grace period handles screen rotations.