0Pricing
Kotlin Academy · 강의

StateFlow: UI를 위한 핫 상태 보유자

StateFlow를 반응형 상태 컨테이너로 사용하고 ViewModels에서 관찰해 보세요.

StateFlow: UI를 위한 핫 상태 보유자은(는) CoddyKit의 무료 Kotlin Academy 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Kotlin Academy 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Kotlin Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

StateFlow란 무엇입니까?

StateFlow는 항상 값을 보유하며 모든 수집기에 업데이트를 내보내는 핫 상태 보유 흐름입니다. 최신 Kotlin 아키텍처에서는 LiveData를 대체합니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val stateFlow = MutableStateFlow(0)  // initial value
    println("Current: ${stateFlow.value}")
    stateFlow.value = 42
    println("Updated: ${stateFlow.value}")
}

MutableStateFlow와 StateFlow 비교

MutableStateFlow는 내부에서 사용하는 변경 가능한 구현입니다. 캐스팅하거나 .asStateFlow()를 사용하여 외부 관찰자에게 읽기 전용인 StateFlow를 노출합니다.

import kotlinx.coroutines.flow.*
class CounterViewModel {
    private val _count = MutableStateFlow(0)  // mutable internally
    val count: StateFlow<Int> = _count.asStateFlow()  // read-only externally
    fun increment() { _count.value++ }
    fun decrement() { _count.value-- }
}

StateFlow 수집

다른 흐름과 마찬가지로 StateFlow를 수집합니다. 수집을 시작하면 최신 값이 즉시 방출됩니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val state = MutableStateFlow("loading")
    launch {
        state.collect { println("State: $it") }
    }
    delay(50); state.value = "success"
    delay(50); state.value = "idle"
    delay(50)
    coroutineContext.cancelChildren()
}

StateFlow는 중복 값을 합칩니다

StateFlow는 값이 변경될 때만 값을 방출합니다. 같은 값을 두 번 설정하면 한 번만 방출됩니다. 연속된 중복 값을 하나로 합치기 때문입니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val flow = MutableStateFlow("A")
    launch {
        flow.collect { println("Received: $it") }
    }
    delay(50)
    flow.value = "A"  // no emission — same value
    flow.value = "B"  // emits
    flow.value = "B"  // no emission — same value
    flow.value = "C"  // emits
    delay(50)
    coroutineContext.cancelChildren()
}

ViewModel에서의 StateFlow

표준 ViewModel 패턴은 다음과 같습니다. 비즈니스 로직이 private MutableStateFlow를 변경하고, UI는 public StateFlow를 관찰합니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
sealed class UiState { object Loading : UiState(); data class Success(val data: String) : UiState(); data class Error(val msg: String) : UiState() }
class MyViewModel(scope: CoroutineScope) {
    private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
    val uiState: StateFlow<UiState> = _uiState.asStateFlow()
    init {
        scope.launch {
            delay(100)  // simulate load
            _uiState.value = UiState.Success("Hello!")
        }
    }
}

원자적 변경을 위한 update()

현재 값을 기준으로 상태를 원자적으로 업데이트하려면 update { }를 사용합니다. 이는 동시에 발생하는 업데이트에서 중요합니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val counter = MutableStateFlow(0)
    List(100) {
        launch(Dispatchers.Default) {
            counter.update { it + 1 }  // thread-safe atomic update
        }
    }.forEach { it.join() }
    println("Counter: ${counter.value}")  // 100
}

낙관적 업데이트를 위한 compareAndSet

compareAndSet(expect, update)는 현재 값이 expect와 일치할 때만 새 값을 설정합니다. 낙관적 동시성 처리에 유용합니다.

import kotlinx.coroutines.flow.*
fun main() {
    val state = MutableStateFlow("idle")
    val changed = state.compareAndSet("idle", "loading")
    println("Changed: $changed, Value: ${state.value}")  // true, loading
    val changed2 = state.compareAndSet("idle", "error")  // won't change
    println("Changed: $changed2, Value: ${state.value}") // false, loading
}

StateFlow와 LiveData 비교

StateFlow는 Android 수명 주기 없이 작동합니다. LiveData는 수명 주기를 인식하지만 Android에서만 사용할 수 있습니다. 공유 KMP ViewModels에는 StateFlow를 권장합니다.

import kotlinx.coroutines.flow.*
// StateFlow: pure Kotlin, works in commonMain
// val state = MutableStateFlow("value")

// LiveData: Android-only, lifecycle-aware
// val liveData = MutableLiveData("value")

// In Compose, collect StateFlow with:
// val state by viewModel.uiState.collectAsState()
fun main() { println("StateFlow: multiplatform; LiveData: Android-only") }

stateIn: 차가운 흐름을 StateFlow로 변환

flow.stateIn(scope, started, initialValue)는 차가운 흐름을 핫 StateFlow로 변환하고, 모든 수집기가 하나의 구독을 공유하게 합니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val cold = flow {
        println("Fetching...")
        delay(100)
        emit("data")
    }
    val hot: StateFlow<String> = cold.stateIn(
        scope = this,
        started = SharingStarted.Lazily,
        initialValue = "loading"
    )
    launch { hot.collect { println("A: $it") } }
    launch { hot.collect { println("B: $it") } }
    delay(200)
    coroutineContext.cancelChildren()
}

SharingStarted 전략

즉시 시작: 바로 시작합니다. 지연 시작: 첫 번째 수집기가 생길 때 시작합니다. WhileSubscribed(stopTimeout): 수집기가 없으면 중지하고, 수집기가 구독하면 다시 시작합니다.

import kotlinx.coroutines.flow.*
// Eagerly: upstream starts right away
// SharingStarted.Eagerly

// Lazily: waits for first subscriber
// SharingStarted.Lazily

// WhileSubscribed: stops 5s after last subscriber
// SharingStarted.WhileSubscribed(5000)

// Typical ViewModel usage:
// val uiState = repo.dataFlow.stateIn(viewModelScope, WhileSubscribed(5000), Loading)

파생 상태 관찰

map + stateIn을 사용하여 기존 StateFlow에서 새로운 StateFlow를 파생합니다. 원본이 변경될 때마다 파생된 흐름이 업데이트됩니다.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val count = MutableStateFlow(5)
    val doubled = count.map { it * 2 }.stateIn(this, SharingStarted.Eagerly, 10)
    println(doubled.value)  // 10
    count.value = 7
    delay(50)
    println(doubled.value)  // 14
    coroutineContext.cancelChildren()
}

빠른 확인

StateFlow에 같은 값을 두 번 설정하면 어떻게 됩니까?

복습

StateFlow는 항상 값을 가지며 중복 값을 합치는 핫 흐름입니다. 내부에서는 MutableStateFlow를 사용하고 외부에는 StateFlow를 노출합니다. 동시에 발생하는 변경에는 update()를 사용하고, 차가운 흐름을 변환할 때는 stateIn()을 사용합니다.

자주 묻는 질문

“StateFlow: UI를 위한 핫 상태 보유자” 강의는 무료인가요?

네 — “StateFlow: UI를 위한 핫 상태 보유자” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Kotlin Academy 강의 전체를 잠금 해제할 수 있습니다. Kotlin Academy 강의에는 총 4개의 강의가 포함되어 있습니다.

“StateFlow: UI를 위한 핫 상태 보유자”에서 뭘 배우나요?

StateFlow를 반응형 상태 컨테이너로 사용하고 ViewModels에서 관찰해 보세요. 브라우저에서 직접 실행하는 실습 코드로 Kotlin Academy을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

Kotlin Academy을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 Kotlin Academy은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.

“StateFlow: UI를 위한 핫 상태 보유자” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 Kotlin Academy 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 Kotlin Academy 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. StateFlow: UI를 위한 핫 상태 보유자
  2. SharedFlow: 이벤트 버스와 일회성 이벤트
  3. shareIn과 stateIn으로 콜드 Flow를 핫 Flow로 변환하기
  4. Turbine으로 StateFlow와 SharedFlow 테스트하기
← Kotlin Academy(으)로 돌아가기