PHpullh
학습 라이브러리/Kotlin/Flow — Cold Stream

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()

학습 팁

StateFlowSharedFlow는 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해야 합니다.