Android 공부/Coroutine

StateFlow, SharedFlow

posite 2026. 2. 20. 14:06

StateFlow

  • 항상 최신의 상태를 담고 있음
  • 구독자가 collect를 하면 값을 전달
  • ViewModel의 상태 관리에 적합함

val countState: StateFlow<Int> = dataStore.countFlow
    .stateIn(
        scope = viewModelScope,
        started = SharingStarted.WhileSubscribed(5000),
        initialValue = 0
    )
lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.countState.collect {
            binding.countText.text = it.toString()
        }
    }
}


SharedFlow

  • 상태를 저장하지 않고 값과 함께 이벤트를 전파함
  • 클릭 이벤트, 네비게이션 요청, 메시지 전파 등에 적합합니다.(단발성)
private val _event = MutableSharedFlow<CounterEvent>()
val event: SharedFlow<CounterEvent> = _event.asSharedFlow()
lifecycleScope.launch {
    repeatOnLifecycle(Lifecycle.State.STARTED) {
        viewModel.event.collect {
            when (it) {
                is MainViewModel.CounterEvent.ShowMaxReached -> {
                    Toast.makeText(
                        this@MainActivity,
                        "Counter reached at 10!",
                        Toast.LENGTH_SHORT
                    ).show()
                }
                is MainViewModel.CounterEvent.ShowMinReached -> {
                    Toast.makeText(
                        this@MainActivity,
                        "Counter is at 0!",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }
}