CodeGym /Các khóa học /Kotlin SELF /Cac toan tu Flow: map, filter, onEach, catch va backpress...

Cac toan tu Flow: map, filter, onEach, catch va backpressure

Kotlin SELF
Mức độ, Bài học
Có sẵn

1. Vi sao can cac toan tu Flow

Khi thay Flow lan dau, ban de muon lam the nay: “minh biet for va if — vay thi cu viet tat ca ben trong collect { ... } la xong”. Cach nay chay duoc, nhung thuong se bien thanh mot handler khong lo, noi tron loc, chuyen doi, in debug va xu ly loi. Mot tuan sau, doan code se trong giong nhu: “minh khong nho cai if nay muon noi gi nua”.

Cac toan tu Flow giup giu cho dau oc gon gang: moi buoc trong pipeline chi phu trach mot y tuong don gian. No gan giong nhu trong nha may: dau tien linh kien toi, sau do qua bo loc chat luong, roi duoc danh dau, roi bo vao hop, va chi den cuoi cung ta moi co san pham hoan chinh.

So do ma hom nay ta huong toi se trong nhu sau:

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

2. Vi du: dong su kien giam sat

De cac vi du lien ket voi nhau, ta se lam mot “he thong giam sat console” nho: ta co cac su kien (vi du "INFO", "WARN", "ERROR"), ta muon chi cho qua nhung cai quan trong, chuyen chung thanh van ban de hieu, doi khi in debug, va khong lam sap ca ung dung chi vi mot loi parse.

Bat dau tu model su kien:

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

Va thong nhat them dinh dang “dong tho” (raw string), nhu the no den tu log: "INFO|Service started" hoac "ERROR|Disk is full".

3. Flow co ban: nguon va collect

Truoc khi vao cac toan tu, nen cam nhan “ong dan tran”: co nguon emit gia tri, va co ben thu gom. Flow chi chay khi collect (nghia la dong du lieu thuc chat la lazy / cold).

Day la dong toi thieu cua “van ban tho”:

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 ...
    }
}

Hien tai day chua phai “bo phan tich”, ma chi la van chuyen gia tri. Bay gio ta se bat dau bien dong nay thanh mot pipeline.

4. Bien doi: map, filter, onEach

map: bien doi va doi kieu

map trong Flow ve y nghia rat giong map cua collection: lay moi phan tu va bien no thanh mot thu gi do moi. Voi Flow y tuong y het, chi khac la cac phan tu den “theo thoi gian”, va qua trinh bien doi co the than thien voi suspend.

Ta se lam parser tu chuoi sang MonitorEvent. De don gian, khong dung Regex, chi dung split.

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

Bay gio ap dung map:

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
        }
}

Hay chu y mot diem quan trong: kieu cua flow da thay doi. Truoc do la Flow<String>, gio thanh Flow<MonitorEvent>. Day la suc manh cua map: no co the doi kieu, va dieu nay lam pipeline bieu dat ro rang hon rat nhieu.

Meo nho de doc code: neu ban bi lac “hien tai flow dang la kieu gi”, hay nho rang map doi kieu, con filter thi thuong khong.

filter: chi giu lai dieu can thiet

Bay gio tuong tuong su kien rat nhieu, nhung ta chi quan tam "WARN" va "ERROR". Luc nay filter len san: chon phan tu theo predicate (lambda tra ve true/false). Voi Flow, y nghia giong het: gia tri hoac di tiep trong pipeline, hoac bi loai bo.

Ta loc sau khi parse:

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
        }
}

O day filter khong doi kieu: flow van la MonitorEvent. No chi “thu hep” tap gia tri.

onEach: side effect ma khong thay doi du lieu

Khi debug flow, ban muon “liếc” xem moi buoc dang lam gi. Y nghi dau tien la nhet println vao map. Nhung do la phong cach khong tot: map ve y nghia nen bien doi du lieu, con in ra chi la side effect.

onEach dung cho viec nay: thuc hien hanh dong voi moi phan tu va cho phan tu di tiep khong thay doi. No giong forEach, nhung nam o giua pipeline cua flow.

Ta them chan doan: hien thi cai gi da qua bo loc.

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}")
        }
}

Diem manh cua onEach la de bo di khi khong can debug, va no khong “pha” y nghia cua map.

Nhan tien, neu ban tung thay println nam trong map, do khong phai toi ac “chet nguoi”, nhung gan nhu luon la dau hieu: “nen lam cho code gon gang lai mot chut”.

5. Loi: catch va pham vi tac dung

catch: xu ly loi trong pipeline

Xu ly loi la thu phan biet “vi du sach giao khoa” voi “chuong trinh song duoc hon 15 giay”. Trong Kotlin ta da biet try/catch va hieu rang exception se cat dut luong thuc thi binh thuong. Trong Flow cung co loi, nhung thuong tien loi hon neu bat loi truc tiep trong pipeline bang toan tu catch.

Lam parser nghiem ngat hon: neu dong khong chua "|", ta coi do la loi dinh dang.

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])
}

Bay gio ap dung catch va “thay the” loi bang mot su kien dac biet:

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}")
        }
}

O day can hieu co che: catch bat cac loi xay ra truoc no trong pipeline (upstream). Nghia la neu loi xay ra trong map { parseLineStrict(it) } thi catch se thay. Con neu loi xay ra muon hon (vi du ben trong collect) thi catch co the khong giup duoc.

Vi sao catch khong bat loi ben trong collect

Day la bay rat thuong gap: ban dat catch, thay yen tam, va nghi flow gio “bat tu”. Nhung catch khong phai o du than ky chong moi tai hoa; no chi bat nhung gi xay ra “o phia tren ong dan”.

Tao loi gia lap ben trong collect:

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")
        }
}

Doan code nay se crash (neu khong boc collect bang try/catch), vi loi xay ra ngay trong consumer. Dieu nay hop ly: collect la thao tac terminal, va neu consumer tu no bi loi thi phai duoc “cuu” boi try/catch ben ngoai, giong nhu trong code binh thuong.

Quy tac thuc te: catch dung cho loi cua nguon va cac toan tu truoc collect. Loi trong handler cua collect thi bat ben ngoai bang try/catch.

6. Backpressure trong Flow

Tu “backpressure” nghe giong ten mot nhom rock (“Backpressure va album moi ‘Suspend Me Gently’”), nhung y nghia rat doi thuong. Neu consumer xu ly gia tri cham, ta muon nguon khong tiep tuc day gia tri ra vo han voi toc do vo ly, neu khong thi hoac ta se “ngop”, hoac bat dau tich dong trong bo nho.

Voi Flow (o mo hinh co ban) co mot co che tu nhien: emit va ca pipeline deu than thien voi suspend, nen neu consumer cham thi upstream thuong se tam dung va cho.

Xem vi du: nguon emit so rat nhanh, con collect xu ly cham bang delay.

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") // in ra "dong bo" theo nhip xu ly
        }
    }.collect { v ->
        delay(100)
        println("collected $v")
        // emitted 0
        // collected 0
        // emitted 1
        // collected 1
        // emitted 2
        // collected 2
    }
}

Neu ban mong thay "emitted 0, emitted 1, emitted 2" xuat hien ngay, roi sau do moi den "collected …", thi do chinh la insight quan trong nhat ve backpressure trong Flow: flow khong bat buoc phai “ban” tat ca ngay lap tuc; no co the tu nhien dong bo voi consumer thong qua cac lan tam dung.

7. Ghepp pipeline thanh mot luong gon gang

Bay gio ta ghep phien ban mini cua “monitor” sao cho code doc giong nhu van ban: “lay cac dong → parse → giu lai cai quan trong → log → bat loi → in ket qua”.

Dau tien lam ham nguon. Trong du an that, su kien den tu ben ngoai, nhung hom nay chi can mo phong:

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")
}

Sau do mo ta pipeline thanh mot ham tra ve Flow<MonitorEvent>. Day la mot phong cach tot: ta tach “lam gi” khoi “xuat ra nhu the nao”.

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}"))
        }

Va main cuoi cung, noi moi thu duoc “gom” lai:

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

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

Hay chu y: doc kieu code nay rat tien. Trong importantEvents() khong co thao tac terminal, nen co the tai su dung, test, va gan vao nhieu cho khac nhau. Con main thi van don gian: “thu thap va in ra”.

8. Bang nho nhanh ve cac toan tu

Khi so luong toan tu tang len, se huu ich neu giu “ban do” trong dau. Ta co mot bang nho:

Toan tu Lam gi Doi kieu flow? Y nghia thuong dung
map { ... }
Bien doi moi gia tri Co “Bien do tho thanh dang de dung”
filter { ... }
Chi cho qua nhung cai phu hop Khong “Chi giu lai cai can”
onEach { ... }
Thuc hien side effect va cho di tiep Khong “Nhin trom/log ma khong doi du lieu”
catch { ... }
Bat loi upstream va dua ra hanh vi thay the Thuong khong (nhung co the emit) “Dung im lang crash, hay xu ly loi”

Neu ban thay mot chain dai, ban co the doc thanh tieng: rawLogLines, map, filter, onEach, catch, collect. Thuong do la dau hieu tot: code giong giai thich hon la mot cau do.

9. Loi thuong gap

Loi #1: lam side effect trong map, roi ngac nhien vi “logic mo ho”.
Khi map vua bien doi du lieu, vua in, vua tinh thong ke, no khong con la “bien doi” nua ma tro thanh “mot cuc tat ca”. Ket qua la kho hieu: dang thay doi cai gi va vi sao. Binh tinh hon la giu map nhu mot transformation “sach”, con in va debug thi dua qua onEach.

Loi #2: dat catch va nghi rang no bat moi thu.
catch bat cac loi xay ra truoc no trong chain, tuc la upstream. Neu loi phat sinh ben trong collect { ... }, do la downstream, va catch co the khong giup duoc. Trong tinh huong nay, tot hon la boc collect bang try/catch, giong nhu luc hoc ve exception.

Loi #3: “nuot” exception trong catch va tiep tuc nhu khong co gi xay ra ma khong co tin hieu nao.
catch {} rong giong nhu dan bang keo den “Check Engine”: xe khong khoe hon, chi la tai xe khong con biet dang co van de gi. Ke ca khi ban phat ra fallback value bang emit, van nen it nhat log thong diep loi hoac tao ro rang mot “su kien loi”, de hanh vi co the doan truoc.

Loi #4: lam toan bo pipeline ben trong collect va tao ra “may gat lien hop” 80 dong.
Code nhu vay kho test va kho tai su dung: logic bi gan chat vao cho xuat. Thuong thi tot hon nen tach pipeline ra mot ham tra ve Flow<...>, con trong main chi giu collect. Cach nay lam code don gian hon va ve cau truc rat giong cac ham xu ly collection, chi khac la theo thoi gian.

Loi #5: mong Flow “ban ra” gia tri nhanh hon toc do consumer xu ly, roi khong hieu vi sao moi thu cham.
Khong phai bug: y tuong co ban cua backpressure la Flow co the tu nhien thich nghi voi toc do xu ly thong qua suspend. Neu trong collect co delay, upstream thuong se “doi” — va dieu do giup khong phinh bo nho va khong tao “lu” su kien.

1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Bình phương năng lượng
Bình phương năng lượng
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Bộ lọc cảm biến
Bộ lọc cảm biến
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Gỡ lỗi lệnh
Gỡ lỗi lệnh
1
Nhiệm vụ
Kotlin SELF, mức độ, bài học
Đã khóa
Bộ phân tích log
Bộ phân tích log
Bình luận
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION