CodeGym /Courses /Kotlin SELF /Reliable event dispatch: snapshot, try/catch, reentrancy

Reliable event dispatch: snapshot, try/catch, reentrancy

Kotlin SELF
Level 57, Lesson 3
Available

1. Why naive dispatch breaks in a real program

When you write emit, it’s very easy to fall into the trap of “it’s just a list, I’ll just iterate over it.” In the first exercises that’s even true. But as soon as your code becomes even a little bit alive, handlers start behaving like real people in a line: someone leaves, someone suddenly brings a friend, and someone faints (throws an exception)—and the line still has to keep moving.

Let’s imagine a naive implementation: it already supports subscribe and unsubscribe, but dispatch is still “fragile.”

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

On the surface everything looks fine. But now let’s add two “ordinary” real-life scenarios.

Scenario: unsubscribe inside a handler

Let the handler be “one-time”: after the first event it removes its subscription.

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

Even without digging deeper, you can see it: during emit the listener list changes. On the JVM, things like that often end badly (like ConcurrentModificationException) or as “silent” logical bugs: somebody gets skipped, somebody gets called an extra time.

Scenario: one handler fails, the others must survive

Suppose you have an audit log and notifications. Notifications crash (for example, a formatting error inside), but the audit must always be recorded.

If emit is not protected, an exception breaks the loop and the remaining handlers won’t be called. And that’s no longer “oops, unpleasant,” it’s “why don’t our reports match?”

2. Listener snapshot: copy the list before dispatch

If you’ve ever tried to take a photo of a cat running around the room, you already understand the idea of a snapshot: you capture “this is how it was at that moment,” and after that the cat can run however it wants—the photo won’t change. In event dispatch, a snapshot is needed for exactly this: we lock in which set of listeners will receive the current dispatch, and subscription changes during dispatch affect only future emit calls.

The key Kotlin tool here is toList(). It creates a copy-list of elements at a specific moment in time; further changes to the source MutableList do not affect the copy.

Bad iteration: a “live” list

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

The problem isn’t that the code is “bad” stylistically. The problem is that it can’t withstand reality, where a handler can mutate the list.

Good iteration: snapshot as the first step

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

And here is a very important rule (almost like “put your own mask on first”): the snapshot must be the first action in emit. If you start dispatching and then suddenly decide to take a snapshot “halfway through,” you’ll get behavior that can’t be explained to a human without resorting to ritual drums.

The snapshot approach contract

With snapshot-based dispatch, we are effectively signing an “agreement” with the users of our Event<T>.

  • If a handler subscribes during emit, it will start receiving events only from the next emit.
  • If a handler unsubscribes during emit, it may still receive the current event (because it is already in the snapshot), but it won’t receive subsequent ones.

This contract is predictable, simple, and can be explained in one paragraph. In educational projects, this is almost always the best choice.

3. try/catch around each handler

There’s a subtle point about exceptions in handlers: we want dispatch to be resilient, but we don’t want to turn errors into a “black hole” where nothing is visible and nobody is responsible. So the correct strategy is usually: catch the exception for each listener separately, record the fact of the error (at least println), and continue dispatching.

Why exactly like this? Because try/catch around the whole dispatch will catch the error, but it will stop the loop. That is, one broken listener breaks everyone else. But if we wrap each listener, the error is isolated.

Incorrect protection: one try/catch for everything

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

It looks “protected,” but in reality: if the first handler fails, the second and third won’t be called.

Correct protection: try/catch per handler

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

Yes, it’s a few more lines. But those lines buy you predictability and survivability of the system.

4. Reentrancy: a handler can call emit again

The word “reentrancy” sounds like we’re about to build a spaceship. In practice the meaning is simple: while processing an event, it can happen that we call emit again—directly or indirectly.

For example, you add an expense → a handler decides the amount is too large → it automatically adds a “fee” as a separate expense → adding the fee also triggers the “expense added” event. Boom: nested dispatch.

We need to ensure that such a scenario doesn’t turn the program into chaos. The snapshot approach already provides a foundation: each emit takes its own copy of the listeners. But it’s worth clearly understanding which effects are possible and which traps remain.

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

One possible output would look like this (the line order depends on where you print):

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

And that’s normal: you really started emit(2) inside emit(1). That means the order becomes “nested,” like function calls. This is exactly what “synchronous dispatch” means.

What snapshot guarantees under reentrancy

Snapshot guarantees that even if, inside emit(1), a handler subscribes or unsubscribes, it won’t break the current iteration. Each emit works with its own copy.

What snapshot does not solve

Snapshot does not save you from infinite recursion. If a handler calls emit again for any value without stopping, you’ll get a stack overflow. That’s not a bug in Event<T>; it’s handler logic.

So for today’s lecture we’ll fix a simple and clear contract: emit is synchronous and allows nested calls, and the responsibility “not to go infinite” lies with the handlers.

5. Assembling a reliable Event<T>

Now let’s carefully assemble the final version of Event<T> that you can use in an educational app. We’ll continue the idea of a console expense tracker: you type “coffee 4.5,” and the app prints “coffee again—hang in there.”

Event model: “expense added”

For simplicity, let’s make a small model:

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

Final Event<T>

Let’s make subscribe return an unsubscribe token, and make repeated unsubscription safe (it won’t crash and won’t try to “remove twice”).

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

Here the snapshot is taken via toList(), which gives us a “snapshot” of listeners at the moment dispatch starts.

try/catch wraps each listener so that one failure doesn’t cut off dispatch for all the others.

Integrating the event into a “mini tracker”

Let’s say we have a service that adds an expense and emits an event:

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

Two independent listeners: audit and “notifications”

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

The expected logic is: “Laptop” will crash the second handler, but the audit must keep working, and the third expense must also be processed.

Example possible output:

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

Notice the behavior: the exception did not “stick” to the whole emit; it is isolated inside a single listener.

Diagram: what happens inside emit

Sometimes it’s useful to see not only the code, but also a “process picture.” Let’s represent dispatch as a conveyor:

flowchart TD
    A["emit(value) called"] --> B["snapshot = listeners.toList()"]
    B --> C["for listener in snapshot"]
    C --> D["try { listener(value) }"]
    D --> E["success → next listener"]
    D --> F["catch Exception → log the error"]
    F --> E
    E --> G["end of dispatch"]

The point of the diagram is one thing: we first lock in the listener list, and then we iterate over the copy, isolating errors from each handler.

6. Common mistakes

Mistake No. 1: taking the snapshot not at the beginning of emit.
Sometimes you’ll see an approach like “I’ll call a couple of listeners first, then I’ll make a copy.” This is almost guaranteed to lead to strange behavior: some listeners will be called using the old list, some using the new one. If you choose the snapshot strategy, the snapshot must be the first step in the dispatch, otherwise you lose the main advantage—predictability.

Mistake No. 2: wrapping the whole emit with a single try/catch.
Such code looks “reliable,” but it protects the wrong thing. When an exception happens, the first failing handler will break the loop, and the other listeners won’t receive the event. The right principle here is isolation: try/catch should wrap each handler, so one failure doesn’t break the whole process.

Mistake No. 3: silently “swallowing” exceptions.
If you catch an exception and do nothing (don’t even print a message), you’re creating an expensive mystery for your future self: “why did one module stop reacting?” In educational code, println is enough; in more serious code, at least record the message and, if possible, the stack trace. The main thing is not to turn errors into invisible ghosts.

Mistake No. 4: expecting that unsubscribing inside emit will instantly cancel the call in the current dispatch.
With the snapshot approach, that’s not the case: the current dispatch is already iterating over a copy. So a handler can receive the event “one more time” within the current emit, even if it just unsubscribed. That’s not a bug; it’s part of the contract. The upside is that the contract is simple and stable: subscription changes affect subsequent dispatches.

Mistake No. 5: accidentally creating infinite reentrancy.
If a handler calls emit again for any event without a stopping condition, you’ll get recursion and eventually a stack overflow. Snapshot doesn’t have to (and can’t) fix this: it’s a logical error in the handler. So for reentrant scenarios, always keep an “exit condition” in mind: a value check, a flag, a limit, or at least plain common sense.

1
Task
Kotlin SELF, level 57, lesson 3
Locked
One-time listener
One-time listener
1
Task
Kotlin SELF, level 57, lesson 3
Locked
Safe event broadcasting
Safe event broadcasting
1
Task
Kotlin SELF, level 57, lesson 3
Locked
Late subscription
Late subscription
1
Task
Kotlin SELF, level 57, lesson 3
Locked
Nested emit
Nested emit
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION