🐦 Kotlin
Advanced
What is Flow.stateIn() in Kotlin?
Answer
Flow.stateIn(scope, started, initialValue) converts a cold Flow into a hot StateFlow that caches the latest value and shares emissions among all collectors within the given scope. It is the standard pattern for exposing repository Flows as StateFlow in a ViewModel: val uiState = repository.dataFlow.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), InitialState). The started parameter (a SharingStarted strategy) controls the upstream collection lifecycle, and initialValue is what new collectors receive before the first emission from the upstream Flow arrives.