PHpullh
학습 라이브러리/Kotlin/Flow 연산자 심화 (combine, merge)

KOTLIN · 비동기

Flow 연산자 심화 (combine, merge)

여러 Flow를 결합하는 고급 연산자입니다. combine은 최신 값을, merge는 모든 방출을 합칩니다.

비동기고급combinemergezipflow-operators

핵심 설명

여러 Flow를 결합하는 고급 연산자입니다. combine은 최신 값을, merge는 모든 방출을 합칩니다.

Kotlin code

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val names = flow {
        emit("김철수"); delay(300)
        emit("이영희"); delay(300)
        emit("박지성")
    }
    val scores = flow {
        emit(85); delay(200)
        emit(92); delay(200)
        emit(78); delay(200)
        emit(95)
    }

    // combine: 양쪽 최신 값 조합
    println("=== combine ===")
    names.combine(scores) { name, score ->
        "$name: $score점"
    }.collect { println(it) }

    // zip: 1:1 매칭
    println("=== zip ===")
    names.zip(scores) { name, score ->
        "$name: $score점"
    }.collect { println(it) }

    // merge: 모든 방출 합치기
    println("=== merge ===")
    val flow1 = flowOf("A", "B").onEach { delay(100) }
    val flow2 = flowOf("1", "2", "3").onEach { delay(150) }
    merge(flow1, flow2).collect { print("$it ") }
}

학습 팁

combine은 어느 한쪽이 새 값을 방출할 때마다 최신 조합을 만듭니다. UI에서 여러 상태를 합칠 때 유용합니다.

주의할 점

zip은 양쪽 모두 방출해야 결합합니다. 한쪽이 완료되면 나머지도 무시되므로 길이가 다른 Flow에 주의하세요.

자주 묻는 질문

Flow 연산자 심화 (combine, merge)란 무엇인가요?

여러 Flow를 결합하는 고급 연산자입니다. combine 은 최신 값을, merge 는 모든 방출을 합칩니다.

Flow 연산자 심화 (combine, merge) 학습 시 주의할 점은 무엇인가요?

zip 은 양쪽 모두 방출해야 결합합니다. 한쪽이 완료되면 나머지도 무시되므로 길이가 다른 Flow에 주의하세요.