KOTLIN · 비동기
Flow — Cold Stream
비동기 데이터 스트림을 선언적으로 처리하는 Kotlin Flow. RxJava를 대체합니다.
비동기고급FlowemitcollectflowOfcatch
핵심 설명
비동기 데이터 스트림을 선언적으로 처리하는 Kotlin Flow. RxJava를 대체합니다.
Kotlin code
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
// flow 빌더 — 구독할 때마다 새로 실행 (cold)
fun temperatureFlow(): Flow<Double> = flow {
while (true) {
val temp = 20.0 + Math.random() * 10
emit(temp)
delay(1000)
}
}
// 변환 연산자
fun main() = runBlocking {
temperatureFlow()
.take(5)
.filter { it > 25.0 }
.map { "⚠️ 고온: ${"%.1f".format(it)}°C" }
.collect { println(it) }
// flowOf — 고정 값 스트림
flowOf(1, 2, 3, 4, 5)
.map { it * it }
.toList()
.also { println(it) }
// catch — 에러 처리
flow<Int> { throw RuntimeException("에러!") }
.catch { e -> emit(-1) }
.collect { println(it) } // -1
// flowOn — 업스트림 Dispatcher 전환
flow { emit(heavyCompute()) }
.flowOn(Dispatchers.Default)
.collect { println(it) }
}
fun heavyCompute() = (1..1000).sum()학습 팁
StateFlow와 SharedFlow는 hot stream입니다. StateFlow는 항상 최신 값을 가지고, SharedFlow는 여러 구독자에게 이벤트를 브로드캐스트합니다.
주의할 점
collect는 flow가 완료될 때까지 현재 코루틴을 중단합니다. 무한 flow라면 take(n)이나 별도 코루틴에서 collect해야 합니다.
자주 묻는 질문
Flow — Cold Stream란 무엇인가요?
비동기 데이터 스트림을 선언적으로 처리하는 Kotlin Flow. RxJava를 대체합니다.
Flow — Cold Stream 학습 시 주의할 점은 무엇인가요?
collect 는 flow가 완료될 때까지 현재 코루틴을 중단합니다. 무한 flow라면 take(n) 이나 별도 코루틴에서 collect해야 합니다.
Continue Learning
Kotlin 학습을 이어가세요
총 200개의 독립 HTML 학습 문서 중 하나입니다. 각 문서는 고유 URL과 canonical 메타데이터를 가집니다.