StateFlow와 SharedFlow는 흐름에서 최적으로 상태 업데이트를 내보내고 여러 소비자에게 값을 내보낼 수 있는 Flow API입니다. 콜드 흐름과 달리 핫 흐름입니다. 수집기와 독립적으로 활성 상태를 유지합니다. 핫 플로우의 작동 방식, 콜드 플로우와의 차이점, stateIn 및 shareIn를 사용하여 콜드 플로우를 변환하는 방법을 알아보려면 Kotlin 문서의 핫 플로우를 참고하세요. 이 페이지에서는 Android 앱에서 StateFlow를 사용하는 방법, 즉 ViewModel에서 UI 상태를 노출하고 UI에서 안전하게 수집하며 StateFlow를 LiveData와 비교하는 방법을 설명합니다.
StateFlow
Android에서 StateFlow는 관찰 가능한 변경 가능 상태를 유지해야 하는 클래스에 아주 적합합니다.
Kotlin 흐름의 예를 따라, View가 UI 상태 업데이트를 리슨하고 구성 변경에도 기본적으로 화면 상태가 지속되도록 LatestNewsViewModel에서 StateFlow를 노출할 수 있습니다.
class LatestNewsViewModel( private val newsRepository: NewsRepository ) : ViewModel() { // Backing property to avoid state updates from other classes private val _uiState = MutableStateFlow(LatestNewsUiState.Success(emptyList())) // The UI collects from this StateFlow to get its state updates val uiState: StateFlow<LatestNewsUiState> = _uiState init { viewModelScope.launch { newsRepository.favoriteLatestNews // Update UI with the latest favorite news // Writes to the value property of MutableStateFlow, // adding a new element to the flow and updating all // of its collectors .collect { favoriteNews -> _uiState.value = LatestNewsUiState.Success(favoriteNews) } } } } // Represents different states for the LatestNews screen sealed class LatestNewsUiState { data class Success(val news: List<ArticleHeadline>) : LatestNewsUiState() data class Error(val exception: Throwable) : LatestNewsUiState() }
MutableStateFlow 업데이트를 담당하는 클래스가 생산자이고, StateFlow에서 수집되는 모든 클래스가 소비자입니다.
새로운 소비자가 흐름에서 수집을 시작하면 스트림의 마지막 상태와 후속 상태가 수신됩니다. LiveData 같이 관찰 가능한 다른 클래스에서 이 동작을 찾을 수 있습니다.
Jetpack Compose에서는 androidx.lifecycle:lifecycle-runtime-compose 아티팩트의 collectAsStateWithLifecycle 컴포저블 함수를 사용하여 StateFlow를 수집합니다. 이 함수는 흐름을 Compose State로 변환하고 수명 주기가 Lifecycle.State.STARTED 아래로 떨어지면 수집을 자동으로 중지합니다. 예시는 수명 주기 인식 흐름 수집을 참고하세요.
뷰에서 다른 흐름과 마찬가지로 repeatOnLifecycle 내에서 StateFlow를 수집합니다.
class LatestNewsActivity : ComponentActivity() { private val latestNewsViewModel: LatestNewsViewModel = TODO() // getViewModel() override fun onCreate(savedInstanceState: Bundle?) { // ... // Start a coroutine in the lifecycle scope lifecycleScope.launch { // repeatOnLifecycle launches the block in a new coroutine every time the // lifecycle is in the STARTED state (or above) and cancels it when it's STOPPED. repeatOnLifecycle(Lifecycle.State.STARTED) { // Trigger the flow and start listening for values. // Note that this happens when lifecycle is STARTED and stops // collecting when the lifecycle is STOPPED latestNewsViewModel.uiState.collect { uiState -> // New value received when (uiState) { is LatestNewsUiState.Success -> showFavoriteNews(uiState.news) is LatestNewsUiState.Error -> showError(uiState.exception) } } } } } }
StateFlow, Flow, LiveData
StateFlow와 LiveData는 비슷한 점이 있습니다. 둘 다 관찰 가능한 데이터 홀더 클래스이며, 앱 아키텍처에 사용할 때 비슷한 패턴을 따릅니다.
그러나 StateFlow와 LiveData는 다음과 같이 다르게 작동합니다.
StateFlow의 경우 초기 상태를 생성자에 전달해야 하지만LiveData의 경우는 그렇지 않습니다.- 뷰가
STOPPED상태가 되면LiveData.observe()는 소비자를 자동으로 등록 취소하는 반면,StateFlow또는 다른 흐름에서 수집하는 경우 자동으로 수집을 중지하지 않습니다. 동일한 동작을 실행하려면 Compose에서collectAsStateWithLifecycle를 사용하거나 뷰의Lifecycle.repeatOnLifecycle블록에서 흐름을 수집합니다.
추가 흐름 리소스
- Android의 Kotlin 흐름
- Android에서 Kotlin 흐름 테스트
- Flow의 shareIn 및 stateIn 연산자에 관해 알아야 할 사항
- LiveData에서 Kotlin Flow로 이전
- 흐름