CodeGym /행동 /Kotlin SELF /Sinrohal su isseun event broadcast: snapshot, try/catch, ...

Sinrohal su isseun event broadcast: snapshot, try/catch, reentrancy

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

1. Wae naivehan broadcast-ga silje program-eseo muneojineunga

emitreul jagsseul ttae, “naegeun geunyang list-igo, geunyang geugeul dora bol ttae” raneun hamjeong-e ppajigi swipda. Cheoeum yeonseup-eseoneun geugeodo jeongmal geureohda. Hajiman code-ga jogeumman deo “saenggyeojimyeon”, handler-deul-i silje queue-e itneun saramcheoreom haengdonghanda: nugu-neun nagago, nugu-neun gapjagi chingu-reul 데려오고, nugu-neun gijeolhanda (exception). Geureonde queue-neun gyesok umjig-yeoya handa.

Naivehan implementation-eul saeng-gaghaja: subscribe-wa unsubscribe-neun jubae gajchugo itjiman, broadcast-neun ajik “fragile”hada.

class Event<T> {
    private val listeners = mutableListOf<(T) -> Unit>()

    fun subscribe(listener: (T) -> Unit): () -> Unit {
        listeners += listener
        return { listeners.remove(listener) }
    }

    fun emit(value: T) {
        for (l in listeners) l(value)
    }
}

Gyeolgwa-neun geotteul-eun areumdapda. Hajiman ije silje saenghwal-eseo jarangseureoun du gae-ui “ilbanjeog” scenario-reul deohae boda.

Scenario: handler naebu-eseo unsubscribe hagi

Handler-ga “one-time”ira-go ha j: cheoeum event han beon hu subscribe-reul haejihanda.

fun main() {
    val e = Event<Int>()

    var unsubscribe: (() -> Unit)? = null
    unsubscribe = e.subscribe { x ->
        println("one-time got $x")   // one-time got 1
        unsubscribe?.invoke()
    }

    e.emit(1)
    e.emit(2)
}

Yeogin jeonmun-euro deureogaji anado boinda: emit jung listener list-ga byeonhanda. JVM-eseo ireon il-eun chajuseo bullpyeonhan gyeolgwa (ye: ConcurrentModificationException)ro ggeutnago, ttoneun “jogeum-ssik” logic bugro ggeutnanda: nugu-reul geonneottwigona, nugu-reul han beon deo bulleotdageona.

Scenario: han handler-ga muneojimyeon, dareun handler-deul-eun sal-a nam-eoya ham

Ye: audit log-wa notification-i itda. Notification-i muneojyeotda (ye: naebu-eseo formatting error). Hajiman audit-eun hangsang gie록 dwaeya handa.

emiti boho dwaeji anh-eumyeon, exception-i loop-reul kkeunh-go, nam-eun handler-deul-eun bul리지 않는다. Igeun ije “a, ggeulkkumhada”ga anira “wae report-ga match-an haji?”da.

2. Listener snapshot: broadcast jeon list boksa tteugi

Bang-aneul ddwijgo inneun gwayang-i-reul chwal-yeonghae bon jeok-i issdamyeon, ije snapshot idea-ga mwonjei-ji algo itda: “geu sungan-e ireoke it-eotda” raneun sajin-eul namgigo, geu hu gwayang-i-ga eotteohge ddwideo sajin-eun an byeonhanda. Event broadcast-eseo snapshot-eun baro geu yongdo다: i beon broadcast-ga eotteon listener jiphap-ege gal geos-inji gojeonghago, broadcast jung subscribe/unsubscribe byeongyeong-eun da-eum emitdeul-e man yeonghyang-eul juneun geos-ida.

Yeogi-eseo Kotlin-ui haeng-bokhan 도구-neun toList()da. I geon teukjeong sungan-ui element-deul-eul boksa-han list-reul mandeulgo, 이후 wonbon MutableListga byeonhaedo boksa-bon-eun yeonghyang badji anh는다.

Nappeun iteration: “live” list

fun emitUnsafe(value: T) {
    for (l in listeners) l(value)
}

Munjega “style”lo nappeuda-neun geosi 아니다. Munjega silje-eseo handler-ga list-reul 바꾸는 상황-eul beotiji 못한다-neun geos-ida.

Jalhan iteration: cheoeum-e snapshot

fun emit(value: T) {
    val snapshot = listeners.toList()
    for (l in snapshot) l(value)
}

Yeogiseo aju jung-yo-han gyuchik-i 있다 (geoui “mask-reul meonjeo jasin-ege sseu-ra” cheoreom): snapshot-eun emite seo cheoeum haengdong-ieoya 한다. Mankeum, broadcast-reul sicakhago nan dwi eojjeodaga “junggan-e” snapshot-eul tteumyeon, salam-ege seolmyeonghaji mot할 jeongdo-ro eenaon haengdong-eul 얻게 된다.

Snapshot approach-ui contract

Snapshot broadcast-reul sseumyeon uri-neun Event<T> user-deul-ege “gyeyak”eul han da go bol su itda.

  • Handler-ga emit jung subscribe-hamyeon, da-eum emitbuteo event-reul badneunda.
  • Handler-ga emit jung unsubscribe-hamyeon, i beon event-neun (이미 snapshot-e iteumyeon) badeul su itjiman, da-eum event-deul-eun badji 않는다.

I contract-neun yes측 가능hago, dan순hago, han dan락-euro ppalli seolmyeong doenda. Gyoyuk project-eseoneun daebubun i geos-i choe선-ui seontaek-ida.

3. Handler mae gega-reul wihan try/catch

Handler-eseo exception-eun seomsehan point-ga 있다: broadcast-ga “resilient”ha길 barajiman, error-reul “black hole”lo mandeulgo sipji-anhta (amu geosdo an boigo, amudo chaegim ani jineun). Geuraeseo bo통 ohu-jeolhan strategy-neun i렇다: listener byeolro exception-eul dae-eulgo, error-ga nat다는 geos-eul 기록한다 (jeo-do println jeongdo), geurigo broadcast-reul gyesok한다.

Wae haneun-ga? try/catchreul broadcast jeonche-reul gamssamyeon error-neun jabjiman loop-ga meomchunda. 즉, han listener-ga dareun listener-deul-eul muneojige handa. Banmyeon listener mae gega-reul gamssamyeon error-ga 격리된다.

Teullin boho: try/catch han beon-e jeonbu

fun emit(value: T) {
    try {
        val snapshot = listeners.toList()
        for (l in snapshot) l(value)
    } catch (e: Exception) {
        println("Emit failed: ${e.message}")
    }
}

Boho-doen deut boijiman, silje-eseoneun: cheot handler-ga muneojimyeon du beonjjae, se beonjjae-neun ije bul리지 않는다.

Olh-eun boho: handler mae gega-re try/catch

fun emit(value: T) {
    val snapshot = listeners.toList()
    for (l in snapshot) {
        try {
            l(value)
        } catch (e: Exception) {
            println("Listener failed: ${e.message}")
        }
    }
}

Matda, jul-i jogeum deo nolda. Hajiman geu juldeul-euro system-ui yes측 가능ham-gwa resilience-reul sanda.

4. Reentrancy: handler-ga emit-eul dasi bul su itda

“Reentrancy”raneun mal-eun deudgi-man haedo 우주선-eul mandeul geot gat지만, silje uimi-neun dan순하다: event 처리가 진행 doejuneun dong-an, uri-ga emiteul dasi hoChul hal su itda — jikjeop tto-neun ganjeop으로.

Ye: expense-reul chuga함 → handler-ga geumaek-i neomu keuda-go 판단함 → 자동으로 “commission”eul dareun expense로 chuga함 → commission chuga-do “expense added” event-reul tto balssa함. Boom: nested broadcast.

Uri-ege jung-yo-han geon, i scenario-ga iss-eodo program-i chaos로 변하지 않는 것. Snapshot approach-neun jubae gineung-eul 준다: mae emiti listener copy-reul jasin-ege gaj는다. Hajiman eotteon effect-ga saenggil su itneunji, geurigo eotteon 함정-i nam-a itneunji-neun myeong확-hi haeya 한다.

Reentrancy example: nested emit

fun main() {
    val e = Event<Int>()

    e.subscribe { x ->
        if (x == 1) e.emit(2)
        println("A got $x")
    }
    e.subscribe { x -> println("B got $x") }

    e.emit(1)
}

Ganeung한 출력 han 가지-neun i렇다 (jul 순서는 eodi-eseo print-haneunji-e ttara 달라질 su 있다):

A got 2
B got 2
A got 1
B got 1

Geu-geon jeong상이다: emit(1) naebu-eseo emit(2)reul jeongmal hoChul 했기 때문이다. 즉, 순서는 함수 call처럼 “nested”doenda. I geos-i baro “synchronous broadcast”ga uimi haneun 바이다.

Reentrancy-eseo snapshot-i bojanghaneun geos

Snapshot-eun emit(1) naebu-eseo handler-ga subscribe/unsubscribe-ha더라도, hyeonjae iteration-eul 망가뜨리지 않는다는 geos-eul bojang한다. Mae emiti jasin-ui copy-e daehae ilhaneunda.

Snapshot-i haegyeolhaji 못하는 geos

Snapshot-eun 무한 recursion-eul 막아 주지 않는다. Handler-ga eotteon 값에 daehaseodo 멈추지 않고 emiteul dasi bulleumyeon, stack overflow-ga nanda. Igeun Event<T> bug-ga anira handler logic이다.

Geuraeseo oneul lecture-eseoneun dan순hago myeong확한 contract-reul jeongri하자: emiteun synchronous-hago nested call-eul heoyong하며, “mu-han-e ppajiji 않기” chaegim-eun handler-ege 있다.

5. Sinrohal su isseun Event<T>reul josimseureopge wanseonghagi

Ije kkeutnae-neun Event<T> beojeon-eul josimseureopge johabhae boda. Gyoyuk app-eseo sseul su iss게 만들 ja. Uri-neun console expense tracker idea-reul 이어간다: yujeo-ga “coffee 4.5”reul 입력하면, app-i “또 coffee네요, 힘내세요”reul 출력하는 sikt이다.

Event model: “expense added”

Dan순-hage jag-eun model-eul mandeulja:

data class ExpenseAdded(
    val id: Int,
    val title: String,
    val amount: Double
)

Final Event<T>

subscribega unsubscribe token-eul 반환하게 하고, dashi unsubscribe-hado anjeon하게 (crash 안 나고 “du 번 삭제”do 시도하지 않게) 만든다.

class Event<T> {
    private val listeners = mutableListOf<(T) -> Unit>()

    fun subscribe(listener: (T) -> Unit): () -> Unit {
        listeners += listener
        var active = true
        return {
            if (active) {
                listeners.remove(listener)
                active = false
            }
        }
    }

    fun emit(value: T) {
        val snapshot = listeners.toList()
        for (l in snapshot) {
            try {
                l(value)
            } catch (e: Exception) {
                println("Listener failed: ${e.message}")
            }
        }
    }
}

Yeogiseo snapshot-eun toList()ro mandeuldeoseo, broadcast 시작 시점-ui listener “sajin”eul 얻는다.

try/catchreul listener mae gega-re 두어서, han 번-ui failure-ga dareun listener-deul-ege broadcast-reul kkeunhji 못하게 한다.

“Mini tracker”e event simeogi

Expense-reul chuga하고 event-reul emit-haneun service-ga it다고 하자:

class ExpenseService {
    private var nextId = 1
    val expenseAdded = Event<ExpenseAdded>()

    fun addExpense(title: String, amount: Double) {
        val e = ExpenseAdded(nextId++, title, amount)
        expenseAdded.emit(e)
    }
}

Du gae-ui 독립 listener: audit-gwa “notification”

fun main() {
    val service = ExpenseService()

    service.expenseAdded.subscribe { e ->
        println("AUDIT: added #${e.id} '${e.title}'") // AUDIT: added #1 'Coffee'
    }

    service.expenseAdded.subscribe { e ->
        if (e.amount > 1000) error("Too big!")        // may crash
        println("UI: +${e.amount} for ${e.title}")    // UI: +4.5 for Coffee
    }

    service.addExpense("Coffee", 4.5)
    service.addExpense("Laptop", 2000.0)
    service.addExpense("Sandwich", 6.0)
}

Gidaeha-neun logic-eun i렇다: “Laptop”i du beonjjae handler-reul muneojige ha겠지만, audit-eun gyesok dwen-da, geurigo 세 번째 expense-do 처리가 되어야 한다.

Ganeunghan 출력 예:

AUDIT: added #1 'Coffee'
UI: +4.5 for Coffee
AUDIT: added #2 'Laptop'
Listener failed: Too big!
AUDIT: added #3 'Sandwich'
UI: +6.0 for Sandwich

I haengdong-eul juj-euiha라: exception-i emit jeonche-e “붙어”버린 geos-i anira, han listener naebu-eseo만 격리되어 있다.

Diagram: emit naebu-eseo mu-eul haneunji

Ttaeron code-man boji 말고 “process picture”reul boneun geosdo yu익하다. Broadcast-reul conveyor로 saeng-gaghaja:

flowchart TD
    A["emit(value) 호출됨"] --> B["snapshot = listeners.toList()"]
    B --> C["for listener in snapshot"]
    C --> D["try { listener(value) }"]
    D --> E["성공 → 다음 listener"]
    D --> F["catch Exception → 오류 로깅"]
    F --> E
    E --> G["방송 끝"]

Diagram-ui 요지는 han 가지다: cheoeum-e listener list-reul 고정하고, geu boksa-bon-e daehae iteration하며, handler mae gega-ui error-reul 격리한다.

6. Jeonhyeongjeog in mistake

Mistake №1: snapshot-eul emit cheoeum-e 하지 않기.
Gakkeum “cheoeum-e listener jom bulleogo, junggan-e boksa”raneun approach-ga 보인다. I geon geu eotteon pyeonghang sungan-e doori gijeokjeok haengdong-eul mandeunda: ilbu listener-neun yets list-ro bul리고, ilbu-neun saeroun list-ro bul린다. Snapshot strategy-reul seontaekhanda면, snapshot-eun 반드시 broadcast cheoeum haengdong-ieoya 한다. Geureoji 않-eumyeon gajang keun 장점인 predictability-reul ileunda.

Mistake №2: emit jeonche-reul han beon-ui try/catch-ro gamssa기.
I code-neun “sinrohal”han deut boijiman, bohohaeya hal geot-eul bohohaji 못한다. Exception-i nasseul ttae cheot handler-ga muneojimyeon loop-ga kkeunhyeo, dareun listener-deul-eun event-reul badji 못한다. Yeogiseo olh-eun 원칙은 isolation이다: try/catchreul handler mae gega-re 두어야 han 번-ui failure-ga jeonche process-reul 망가뜨리지 않는다.

Mistake №3: exception-eul mall-eopsi “swallow”hagi.
Exception-eul catch-ha-go amu geosdo 하지 않-eumyeon (메시지도 출력 안 함), 미래-ui jasin-ege bi싼 mystery-reul 남긴다: “wae eoneu module-i ban응-eul meomchuwotji?” Gyoyuk code-eseoneun printlnjeongdo면 충분하고, deo serius-han code-eseoneun jeo-do messagewa (ganeunghamyeon) stack-eul 기록하라. 핵심은 error-reul 보이지 않게 만들지 않는 것.

Mistake №4: emit jung unsubscribe-ha면 hyeonjae broadcast-eseo geu handler call-i dangjang chwi소될 geos-eul 기대하기.
Snapshot approach-eseoneun geureohji 않다: hyeonjae broadcast-neun imi copy-reul dorago 있다. Geuraeseo handler-ga 방금 unsubscribe-haet더라도, hyeonjae emit 범위 안에서 “han beon deo” event-reul badeul su 있다. Igeun bug-ga 아니라 contract-ui ilbu다. 장점은 contract-ga dan순하고 stable-h다는 것: subscribe/unsubscribe byeongyeong-eun da-eum broadcast-deul-e yeonghyang-eul 준다.

Mistake №5: sil수로 muhan reentrancy-reul mandeulgi.
Handler-ga eotteon event-e daehaseodo jogeon eopsi emiteul dasi bulleumyeon, recursion-i saenggigo gyeolguk stack overflow-ga nanda. Snapshot-eun i geos-eul (haeya hal 의무도 없고, hael sudo) 고치지 못한다: i geon handler logic error다. Geuraeseo reentrant scenario-reul 다룰 ttaen hangsang “exit condition”eul meori soge dua라: 값 체크, flag, limit, tto-neun jeo-do 상식.

1
과제
Kotlin SELF, 레벨 57, 레슨 3
잠금
일회성 리스너
일회성 리스너
1
과제
Kotlin SELF, 레벨 57, 레슨 3
잠금
안전한 이벤트 전파
안전한 이벤트 전파
1
과제
Kotlin SELF, 레벨 57, 레슨 3
잠금
지연된 구독
지연된 구독
1
과제
Kotlin SELF, 레벨 57, 레슨 3
잠금
중첩된 emit
중첩된 emit
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION