CodeGym /행동 /Kotlin SELF /Flow operator: map, filter, onEach, catch, geurigo backpr...

Flow operator: map, filter, onEach, catch, geurigo backpressure

Kotlin SELF
레벨 54, 레슨 3
사용 가능

1. wae Flow operator-ga piryohan-ga

Flowreul cheoeum bomyeon, son-i ireohge ganda: “na-neun forwa ifreul hal jul ani, geureom geunyang collect { ... } an-e da sseumyeon doejana.” Geuge doedoe, hajiman botong han beon-e keun handler hana-ro byeonhae, geu an-e filter, transform, debug print, error cheori-ga seokyeo beorinda. Ilju il hueneun geu code-ga “i ifro mwo-reul malharyeotdeora?”cheoreom boinda.

Flow operator-neun saenggak-eul jeongdonhage haejunda: paipeline-ui gakkak step-eun han gaji dan순han aidee-man damdanghanda. geolchyeo bo면 gongjang-gwa biseuthada: cheoeum-e bu품-i deureoogomyeon, pume jil filter-reul geochigo, da-eum mark-reul jjikgo, da-eum sangja-e neohgo, majimak-e wanseongpum-eul badneunda.

oneul uri-ga jirophage doel “mok표” schem-eun ireohda:

flowchart LR
    A["Source flow { emit(...) }"] --> B["filter {...}"]
    B --> C["map {...}"]
    C --> D["onEach {...}"]
    D --> E["catch {...}"]
    E --> F["collect {...}"]

2. yeje: monitoring event stream

yejedeul-eul seoro yeongyeolhagi wihae jageun “console monitoring system”eul mandeulja: event(ye: "INFO", "WARN", "ERROR")ga issgo, uri-neun jungyohan geotman tonggwahage h고, geodeul-eul iy해hagi swipge text-ro byeonhwanhago, gakkeum debug-reul chulryeokhago, parsing error han beon-e app-jeonche-ga muneojiji anhge h고 sipda.

cheoeum-e event model-eul mandeulja:

data class MonitorEvent(
    val level: String,
    val message: String
)

geurigo “raw line” format-eul hwana jeonghaja. log-eseo wasseotdago saenggakhamyeon: "INFO|Service started" ttoneun "ERROR|Disk is full".

3. gibon Flow: sourcewa collect

operator-eul sseugi jeon-e “naked pipe”reul meonjeo 느껴boda: value-reul emit haneun source-ga issgo, geugeul badeuneun collector-ga itda. Flowneun collecthaeya-man si작handa (즉, stream-eun bonjiljeok-euro lazy / cold).

gajang dan순han “raw text” stream-eun ireohda:

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    val lines = flow {
        emit("INFO|Service started")
        emit("WARN|Cache miss")
    }

    lines.collect { line ->
        println("raw: $line") // raw: INFO|Service started ...
    }
}

jigeum-eun “analyzer”ga anira, geunyang value delivery-il ppun이다. 이제 stream-eul paipeline-euro 바꾸기 sijakha겠다.

4. byeonhwan: map, filter, onEach

map: byeonhwan mit type byeongyeong

Flowui mapeun collection-ui mapgwa uimidoe-ro mae우 biseuthada: gakkak element-reul bada seo ro da-eun muneuro bakkunda. Flowdo aidee-neun gatjiman, element-ga “siganyeul ttaraseo” deureoogo, byeonhwan-i suspend chinwha-jeok-ildo hal su itda.

line-eul MonitorEventro parsing haneun function-eul mandeulja. dan순hagi wihae Regexneun sseuji 않고, bo통-ui splitman sse겠다.

fun parseLine(line: String): MonitorEvent {
    val parts = line.split("|", limit = 2)
    val level = parts[0]
    val message = parts.getOrElse(1) { "" }
    return MonitorEvent(level = level, message = message)
}

ijen mapeul jeokyonghae boda:

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    flow {
        emit("INFO|Service started")
        emit("ERROR|Disk is full")
    }
        .map { parseLine(it) }
        .collect { e ->
            println("${e.level}: ${e.message}")
            // INFO: Service started
            // ERROR: Disk is full
        }
}

yeogi-seo jungyohan point: stream-ui type-i bakkwiesseul. jeon-eun Flow<String>, ijen Flow<MonitorEvent>. ige mapui “chulryeok”ida: type-eul bakkul su isseoseo paipeline-eul deo uimiroun hyungtae-ro mandeunda.

code ilggi tip: “jigeum stream-ui type-i mwoji?”ga he갈릴 ttaen, mapeun type-eul bakkul su 있고, filterneun botong geureohji anhdaneun jeomeul tte올려라.

filter: piryohan geotman 남기gi

ijen event-ga maneunda-go ha자. hajiman uri-ga gwan심 itneun geos-eun "WARN"gwa "ERROR"man irago ha자. yeogi-seo filterga dongjak한다: predicate( true/falsereul return haneun lambda )ro element-reul seontaek한다. Flowdo uimi-neun ttokgatda: value-ga paipeline-ui daeum dan-gye-ro gageona, 아니면 beoryeojinda.

parsing hu-e filter-reul geolja:

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    flow {
        emit("INFO|Service started")
        emit("WARN|Cache miss")
        emit("ERROR|Disk is full")
    }
        .map { parseLine(it) }
        .filter { e -> e.level != "INFO" }
        .collect { e ->
            println("IMPORTANT: ${e.level} ${e.message}")
            // IMPORTANT: WARN Cache miss
            // IMPORTANT: ERROR Disk is full
        }
}

yeogi-seo filterneun type-eul bakkugi anh는다: MonitorEvent stream-eun geudaero. danji value set-eul “juliginda”.

onEach: data-neun geudaero, side effect-man

stream-eul debugging hal ttae, gakkak step-eseo mueos-i ireona-neunji “ssaljjak” bogo sipda. cheoeum saenggak-eun map an-e printlneul neohneun geos. hajiman geugeun style-i an johda: mapeun data 변환-i bonjil, printneun side effect-igi ttaemun이다.

onEachga geureol ttae sseunda: gakkak element-e daehae action-eul ha고, element-reul byeonhyeong eopsi daeum-euro heulleonae boda. collection-ui forEachwa biseuthajiman, flow paipeline junggan-e kkoeo 넣neun geos이다.

diagnostic-eul deohae: filter-reul 통gwahan geosi mueos-inde ji boyeojugi.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    flow {
        emit("INFO|Service started")
        emit("WARN|Cache miss")
        emit("ERROR|Disk is full")
    }
        .map { parseLine(it) }
        .filter { it.level != "INFO" }
        .onEach { println("debug: passed filter -> $it") }
        .collect { e ->
            println("ALERT: ${e.message}")
        }
}

onEachui 장점-eun debugging-i piryohaji anheul ttae swipge ji울 su 있고, mapui uimi-reul “mangchiji” anhneunda-neun geos이다.

chamgo-ro, map an-e printlni itneun code-reul bo게 doemyeon: jeoldae jeok, “juk-eul joe”gaji-neun anijiman, dae부분 igeu signal이다: “i code-neun jom 정리hae야 한다”.

5. error: catchwa geu yeongyeong-ui gyeonggye

catch: paipeline-eseo error cheori

error cheori-neun “gyojae 예제”wa “15cho isangeul beotineun program”eul guraeneun yeokhal-eul 한다. Kotlin-eseo uri-neun try/catchreul imi algo 있고, exception-i balsaenghamyeon jeongsang flow-ga kkeun-khinda-neun geos-eul ihaehanda. Floweseodo error-ga balsaenghal su issjiman, manheun gyeongu operator catch로 paipeline 안에서 바로 jabneun geosi pyeonhada.

parser-reul deo 엄격hage mandeulja: line-e "|"ga eops-eumyeon format error-ro 본다.

fun parseLineStrict(line: String): MonitorEvent {
    val parts = line.split("|", limit = 2)
    if (parts.size < 2) error("Bad format: '$line'")
    return MonitorEvent(level = parts[0], message = parts[1])
}

ijen catchreul jeokyonghago, error-reul teukbyeolhan event-ro “dae체”hae boda:

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    flow {
        emit("INFO|Service started")
        emit("BROKEN LINE")
        emit("ERROR|Disk is full")
    }
        .map { parseLineStrict(it) }
        .catch { e ->
            println("handled error: ${e.message}") // handled error: Bad format: 'BROKEN LINE'
            emit(MonitorEvent("ERROR", "Parser failed, but app continues"))
        }
        .collect { e ->
            println("event: ${e.level} ${e.message}")
        }
}

yeogi-seo haeya hal ihae: catchneun paipeline-eseo jagi ap (upstream)eseo balsaenghan error만 jab는다. 즉, map { parseLineStrict(it) }eseo error-ga teojimyeon catchga bon다. hajiman error-ga geu dwae (ye: collect an)eseo balsaenghamyeon, catchga 도와주지 못할 su itda.

wae catchga collect an-ui error-reul 못 잡neun-ga

igeon ja주 나오는 함정이다: catchreul 달아두고 안심해서, ijen stream-i “anmangchyeojinda”고 생각한다. hajiman catchneun modeun munje-ui 만능 우산-i 아니다. “pipe 위쪽”에서 일어난 것만 잡는다.

collect an-e seo in위jeok error-reul mandeulja:

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    flow {
        emit(1)
    }
        .catch { println("catch: ${it.message}") }
        .collect { _ ->
            error("boom in collect")
        }
}

i code-neun ( collectreul try/catchro gamssaji 않는다면 ) crash 난다. iyu-neun error-ga 이미 consumer 안에서 balsaenghaetseugi ttaemun이다. 논리jeok이다: collectneun terminal operation이고, consumer 자체가 넘어지면 바깥쪽 try/catchga jabeoya 한다 — ilban codewa ttokgatda.

siljeon gyuchik: catchneun sourcewa operator ( collect jeon ) error cheori용. collect handler 안에서 난 error는 바깥에서 일반 try/catch로 잡아라.

6. Floweseo-ui backpressure

backpressure-raneun dan-eoneun rock band ireum- gata (“Backpressure and their new album ‘Suspend Me Gently’”), hajiman uimineun mae우 il상jeok이다. consumer-ga value-reul 느리게 cheori하면, source-ga muhanhi ppalli value-reul naejunaej지 않게 hagireul baranda. geureohji 않으면 uri-neun either “gulg-eopsi” bu하-ga 걸리거나, memory-e value-reul ssah게 된다.

Flowui (gibon model-eseo) jayeonseureon mechanism-i 있다: emitgwa paipeline jeonche-ga suspend chinwha-jeok-iigi ttaemun-e, consumer-ga 느리면 upstream-i ilsi jeongji하고 기다리는 gyeongu-ga manh다.

yejereul bossa: source-neun sujareul ppalli emit h고, collectneun delayro 느리게 cheori한다.

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    flow {
        repeat(3) { i ->
            emit(i)
            println("emitted $i") // printing stays "in sync" with processing
        }
    }.collect { v ->
        delay(100)
        println("collected $v")
        // emitted 0
        // collected 0
        // emitted 1
        // collected 1
        // emitted 2
        // collected 2
    }
}

man약 "emitted 0, emitted 1, emitted 2"ga meonjeo 한꺼번에 찍히고, geu da-eum-e "collected …"ga ttar올 geot-gatd다면, 바로 geuge backpressure-e dae한 Flowui haeksim insight이다: stream-eun modeun geot-eul “sunsikgan-e ss아” naegobul pil-yo-ga 없다. suspendreul tonghae consumerwa jayeonseureopge sync-doel su 있다.

7. paipeline-eul kkalkkeumhan pipeline-uro guchyeonghagi

ijen uri “monitor”ui mini version-eul guchyeonghae, code-ga munjang cheoreom ilg히ge hae boda: “line-eul bada → parse → 중요한 것만 남기고 → log → error 잡고 → 결과 출력”.

meonjeo source function-eul mandeulja. siljeon-e seo event-neun oegbu-eseo deureo 오지만, oneul-eun simulation man-euro chungbun하다:

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow

fun rawLogLines(): Flow<String> = flow {
    emit("INFO|Service started")
    emit("WARN|Cache miss")
    emit("BROKEN LINE")
    emit("ERROR|Disk is full")
}

geu da-eum, paipeline-eul Flow<MonitorEvent>reul return haneun function-euro seolmyeongha자. ige joheun style이다: “mueos-eul 할ji”wa “eotteoke 출력할ji”reul 분리한다.

import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.catch

fun importantEvents(): Flow<MonitorEvent> =
    rawLogLines()
        .map { parseLineStrict(it) }
        .filter { it.level != "INFO" }
        .onEach { println("trace: $it") }
        .catch { e ->
            emit(MonitorEvent("ERROR", "stream failed: ${e.message}"))
        }

majimak maineseo mo두 guchyeong된다:

import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect

fun main() = runBlocking {
    importantEvents().collect { e ->
        println("ALERT: ${e.level} -> ${e.message}")
    }
}

yeogi-seo bogo ga야 할 jeom: importantEvents() 안에는 terminal operation-i eops다. geureom reusable, test 가능, darun 곳에도 이어붙일 su 있다. 반면 maineun dan순해진다: “mo아서 출력”.

8. operator memo

operator-ga manh-a jimeon, meori 속에 “지도”reul du-myeon jo다. jageun table-ro jeongniha자:

Operator mueos-eul 하는가 Stream type-eul bakkuneun-ga? typical meaning
map { ... }
gakkak value-reul byeonhwanhanda ye “raw-reul 쓰기 편한 형태로 바꿔라”
filter { ... }
조건에 맞는 것만 통과시킨다 aniyo “필요한 것만 남겨라”
onEach { ... }
side effect-reul 하고 다음으로 넘긴다 aniyo “data-neun bakkugi 없이 엿보기/로그 남기기”
catch { ... }
upstream error-reul 잡고 alternative behavior-reul 준다 botong aniyo (hajiman emithal su itda) “조용히 죽지 말고, error-reul 처리하라”

gireun chain-eul bomyeon, geunyang sorinae seo ilg-eo-do 된다: rawLogLines, map, filter, onEach, catch, collect. botong ige “good sign”이다: code-ga suksu끼-ga anira seolmyeong cheoreom bo인다.

9. jaju 하는 실수

sil수 № 1: map an-e side effect-reul 넣go, 나중에 “logic-i wae ireonji”rago 당황하기.
mapi data도 bakkugo, print도 하고, 통계도 내면, 더 이상 “변환”이 아니라 “모든 것의 덩어리”가 된다. geureom mueos-eul wae bakkuneunji 파악하기가 어려워진다. mapeun pure transformation-euro du고, print/debug-reul onEachro bunrihae dua-myeon 훨씬 안정적이다.

sil수 № 2: catchreul 달아두고, geuge “정말 모든 것”을 잡는다고 믿기.
catchneun chain-eseo 자기 앞(upstream)에서 일어난 error만 잡는다. man약 error-ga collect { ... } 안에서 balsaenghamyeon, geuge downstream이고, catchga 도움이 안 될 수 있다. 이럴 때는 collect 바깥을 일반 try/catch로 감싸는 편이 낫다 — 예외를 배울 때 하던 방식 그대로.

sil수 № 3: catch에서 exception을 “삼켜버리고”, 아무 일도 없었던 것처럼 신호 없이 계속하기.
bi-eo itneun catch {}neun, “Check Engine” bul-eul 테이프로 가리는 것과 같다: 차가 나아지는 것은 아니고, 운전자는 무슨 일이 일어나는지 더 못 보게 된다. emit으로 fallback value-reul 주더라도, 적어도 error message-reul 남기거나 “error event”reul 명시적으로 만들어, 동작이 예측 가능하도록 하자.

sil수 № 4: paipeline jeonche-reul collect 안에서 처리해서, 80줄짜리 “combinator”를 만들기.
geureon code-neun test하기도 어렵고 재사용도 어렵다: 로직이 출력 위치에 강하게 묶인다. 대부분은 paipeline-eul Flow<...>reul return haneun function-euro 빼고, main에는 collect만 남기는 게 낫다. 구조가 더 단순해지고, 시간축 위에서 동작한다는 점만 빼면 컬렉션 처리 함수들과 매우 비슷한 형태가 된다.

sil수 № 5: Flowga consumer 처리 속도보다 더 빨리 값을 “쏴줄” 거라고 기대하고, 왜 느린지 이해 못하기.
igeon bug-ga 아니다: backpressure-ui gibon aidee-neun Flowga suspendreul tonghae 처리 속도에 자연스럽게 맞춰 준다는 데 있다. collect 안에 delayga 있으면, upstream-i 자주 “기다리게” 된다 — 그리고 그게 바로 메모리를 부풀리지 않고 이벤트 눈사태를 막아 주는 장치다.

1
과제
Kotlin SELF, 레벨 54, 레슨 3
잠금
에너지 제곱
에너지 제곱
1
과제
Kotlin SELF, 레벨 54, 레슨 3
잠금
센서 필터
센서 필터
1
과제
Kotlin SELF, 레벨 54, 레슨 3
잠금
명령 디버깅
명령 디버깅
1
과제
Kotlin SELF, 레벨 54, 레슨 3
잠금
로그 파서
로그 파서
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION