PHpullh
학습 라이브러리/Kotlin/Flow 수집 연산자 (Terminal Operators)

KOTLIN · 비동기

Flow 수집 연산자 (Terminal Operators)

Flow의 터미널 연산자인 collect, toList, first, reduce, launchIn 등을 다룹니다.

비동기중급flow-terminalcollectreducelaunchIn

핵심 설명

Flow의 터미널 연산자인 collect, toList, first, reduce, launchIn 등을 다룹니다.

Kotlin code

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

fun numbers(): Flow<Int> = flow {
    for (i in 1..10) {
        delay(50)
        emit(i)
    }
}

fun main() = runBlocking {
    // toList: 전체 수집
    val list = numbers().toList()
    println("리스트: $list")

    // first / firstOrNull
    val first = numbers().first { it > 5 }
    println("첫 번째 >5: $first")

    // reduce / fold
    val sum = numbers().reduce { acc, value -> acc + value }
    println("합: $sum")

    val product = numbers().take(5).fold(1) { acc, value -> acc * value }
    println("곱(1~5): $product")

    // count
    val evenCount = numbers().count { it % 2 == 0 }
    println("짝수 개수: $evenCount")

    // launchIn: 별도 코루틴에서 수집
    val job = numbers()
        .onEach { print("$it ") }
        .onCompletion { println("
수집 완료") }
        .launchIn(this)
    job.join()
}

학습 팁

launchInscope.launch { flow.collect {} }의 축약형입니다. UI 이벤트 처리에 자주 사용됩니다.

주의할 점

first()에 조건을 만족하는 원소가 없으면 NoSuchElementException이 발생합니다. 안전하게 firstOrNull()을 사용하세요.

자주 묻는 질문

Flow 수집 연산자 (Terminal Operators)란 무엇인가요?

Flow의 터미널 연산자인 collect , toList , first , reduce , launchIn 등을 다룹니다.

Flow 수집 연산자 (Terminal Operators) 학습 시 주의할 점은 무엇인가요?

first() 에 조건을 만족하는 원소가 없으면 NoSuchElementException 이 발생합니다. 안전하게 firstOrNull() 을 사용하세요.