CodeGym /Courses /Kotlin SELF /Event-driven thinking — loose coupling and the event cont...

Event-driven thinking — loose coupling and the event contract

Kotlin SELF
Level 57, Lesson 0
Available

1. Introduction

Today we start looking at programs as a system where “something happened” matters more than “someone called someone”. We’ll figure out how to replace direct calls between parts of the code with publishing an event, how the roles of event sources and listeners appear, and why a pre-agreed event contract saves a project from chaos. Then, in the next lectures, we’ll gradually make events convenient, safe, and suitable for a coroutine-oriented world.

When code starts to “stick”

If you’re writing a learning console program in 50 lines, it may seem like architecture was invented for boring people in ties. But here’s the bad news: as soon as you add a second or third “side effect” (logging, stats, saving to a file, notification), the code starts behaving like chewing gum under a desk: it kind of holds, but it’s unpleasant to touch.

Let’s imagine our hands-on project — a hypothetical console expense tracker BudgetBuddy. We have an add command that adds an expense. The naive approach is: “if we added it — then we log right away, recalculate the report right away, save right away, and print a message right away.”

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

fun addExpense(expenses: MutableList<Expense>, e: Expense) {
    expenses += e
    println("Added: ${e.title} (${e.amount})") // Added: Coffee (250)
    println("Audit: expense added id=${e.id}") // Audit: expense added id=1
    println("Stats: need to recalc totals")    // Stats: need to recalc totals
}

The code works. It even seems kind of cute. And then you add “one more small reaction” — for example, auto-saving to a file — and addExpense turns into a combine harvester.

The problem isn’t that it has many lines. The problem is that addExpense starts knowing too much: what audit is, what stats are, when to save, what format to log in. It’s no longer “add an expense”, it’s “add an expense and do a hundred more things, because life is pain”.

An event is a fact, not a command

When the word event/“event” appears in code, beginners often perceive it as “some magic that flies through the air”. In reality, it’s simpler and more down-to-earth: an event is a message about a fact, not an order to a specific module. The difference is subtle, but it changes the architecture radically.

Compare two phrasings:

  • “Send an email to the user” — that’s a command: you’ve already chosen who and what should be done.
  • “The user has registered” — that’s a fact; then different parts of the system can react in their own way.

In our BudgetBuddy, the “command” would look like this: sendEmailToAccountant(expense) (yes, accountants are people too). And the “fact” would sound like: expenseAdded(expense).

That’s loose coupling: the part of the code that adds an expense doesn’t have to know that somewhere there is auditing, reports, or auto-saving. It reports the fact: “expense added”. And then — whoever heard it, good for them.

2. The “one → many” model: source and listeners

In an event-driven model there is almost always the same picture: there is an event source (publisher/emitter) that publishes a fact, and there are listeners (listeners/observers) that react to that fact. And there may be one listener, two, or twenty — and the source shouldn’t nervously hiccup because of it.

Minimal implementation with a collection of handlers

To feel the idea with your hands, you don’t need any libraries or frameworks. A collection of handlers is enough. Collections in Kotlin exist precisely for this: to store a set of elements and allow adding/removing them. MutableCollection has operations to change its contents (for example, add/remove), and this is the foundation for a “subscriber list”.

A minimal “one → many” model can look like this:

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

val expenseAddedListeners = mutableListOf<(Expense) -> Unit>()

fun addExpense(expenses: MutableList<Expense>, e: Expense) {
    expenses += e
    for (listener in expenseAddedListeners) listener(e)
}

This isn’t an “ideal” event implementation yet (we’re not discussing safety, unsubscribing, or handler errors yet). But as an educational picture — excellent: we added an expense, iterated over the listeners, and each one performed its reaction.

Important: we intentionally use mutableListOf because the subscriber list changes: someone subscribes, someone disconnects. Kotlin is fine with storing a mutable collection in a val: the reference doesn’t change, but the contents do. It’s like “the box is always the same, but candies inside appear and disappear”.

Hooking up reactions separately

Let’s spell out what exactly gets better when we stop “tugging neighbors by the sleeve” and start publishing events.

Imagine we have three reactions to adding an expense: printing to the console, auditing, and recalculating stats. In the direct approach, addExpense must know about all three. In the event-driven approach, addExpense only knows about the fact of adding, and the reactions live separately.

fun printOnAdded(e: Expense) {
    println("Added: ${e.title} (${e.amount})") // Added: Coffee (250)
}

fun auditOnAdded(e: Expense) {
    println("Audit: expense id=${e.id}")       // Audit: expense id=1
}

fun statsOnAdded(e: Expense) {
    println("Stats: recalc after ${e.title}")  // Stats: recalc after Coffee
}

Wiring up listeners looks like this:

fun main() {
    expenseAddedListeners += ::printOnAdded
    expenseAddedListeners += ::auditOnAdded
    expenseAddedListeners += ::statsOnAdded
}

And here a nice thing appears: to add a new reaction, we don’t need to touch addExpense. We add a new listener function and subscribe it. The program grows, but the “center” of the system doesn’t turn into a monster that knows everything about everything.

3. The event contract and the rules of the game

When people first hear about events, they often get the feeling: “Oh, cool, now we can just ‘emit’ whatever we want, wherever we want, and everything will work by itself.” That’s a dangerous illusion. Events work well only when they have a contract — i.e., a set of pre-agreed rules that everyone follows.

A contract is not necessarily a formal 20-page document. In a learning project, it can be just a clear agreement in your head and in the code. But you need to resolve the questions in advance, because otherwise different parts of the program will start expecting different behavior.

What’s included in the contract

Below is a table of “what to agree on”, without diving into the implementation (we’ll do the implementation in the next lectures).

Contract part Question Why it matters
Event data (payload) What do we pass to listeners: a string, a number, an object? If you pass “magic strings”, it’s easy to make mistakes. A dedicated data type makes the meaning explicit.
Synchrony Are listeners called “right now” or “sometime later”? If it’s synchronous, a listener can slow down the main operation. If it’s asynchronous, questions about ordering and lifecycle appear.
Listener errors If one listener fails, should the others still run? Without an agreement you’ll get random failures: “sometimes it works, sometimes it doesn’t”.
Invocation order Is there a guaranteed listener order? If order matters, you’re effectively building a pipeline, which is a different style.
Subscription management Can you subscribe/unsubscribe while the program is running? Otherwise you risk “eternal listeners” that get called when they’re no longer needed.
Behavior when there are no listeners What does the event do if no one is subscribed? It’s fine if it’s “nothing”. That makes the code predictable.

Notice: we’re not yet saying “how exactly” to implement unsubscribing or safe dispatch. We’re only stating: this is part of the contract, and without it an event system quickly turns into mysticism where everything works only on Fridays.

How to name events

A funny thing happens with an event name: it influences the team’s thinking more than it seems. If you name the event sendEmail, you’ve already baked into the architecture that “event = email”. That breaks the idea of loose coupling, because the source is basically hinting: “I expect you to send an email.”

It’s better to name an event as a fact, usually in the past tense or in the form “what happened”:

  • expenseAdded / ExpenseAdded
  • expenseRemoved
  • reportGenerated

And it’s useful to think like this: “An event must be true.” If the event is called expenseAdded, then at the moment of publication the expense has indeed already been added to the list/storage. If you publish the event before the state change, listeners may see the “world before the change” and start making decisions based on stale data. That’s not a bug — it’s a classic design trap.

A mini-example of the correct order: first change the state, then publish the fact.

fun addExpense(expenses: MutableList<Expense>, e: Expense) {
    expenses += e
    for (listener in expenseAddedListeners) listener(e)
}

Extract a “fact point” in the code

Now we’ll take a very important step that looks almost comically simple: we’ll separate “adding an expense” from “all reactions”. Not via a full Event<T> (that will come later), but via an explicit function — an “event point”. This is a useful intermediate style: you’re already disciplining the code even if you don’t yet have subscription infrastructure.

fun emitExpenseAdded(e: Expense) {
    println("Event: expenseAdded(id=${e.id})") // Event: expenseAdded(id=1)
}

fun addExpense(expenses: MutableList<Expense>, e: Expense) {
    expenses += e
    emitExpenseAdded(e)
}

Why do this at all if “no one is listening” yet? Because you fix the architectural meaning: the fact happened here. Later, when listeners appear, you’ll replace the body of emitExpenseAdded with dispatch to subscribers, and you won’t have to plow through the rest of the code.

And this is exactly the moment when the system starts to “unclench”: addExpense stops being the place where people add “one more reaction”. It becomes the place where the domain action happens (an expense was added) and a fact is published.

4. Trade-offs: the price of flexibility and where events aren’t needed

Events are not free. They give flexibility, but take away some simplicity. And if you don’t say that out loud, at some point you’ll start suspecting that “events are evil” because everything became non-obvious. In reality, you just didn’t pay the bill: you didn’t define the contract and didn’t discipline usage.

The main cost is that execution becomes less linear. With a direct call, you read code top to bottom and roughly understand: “first we added, then recalculated, then saved”. With events, you read: “we added, and then… somewhere someone reacted”. That’s normal, but it takes a habit: now behavior is defined not by one place, but by a set of subscriptions.

The second cost is managing the lifecycle of listeners. If subscriptions live longer than needed, you get unexpected repeated reactions. If a listener fails with an exception, you must understand what happens to the others. If a listener subscribes/unsubscribes during dispatch, you need to decide in advance how the system should behave. We’re not solving these tasks yet, but it’s important to see them as real engineering questions rather than “we’ll somehow deal with it later”.

And one more limitation that’s useful to keep in mind: events are great for extensible “one → many” reactions, where listeners can appear and disappear. But if you need a simple result like “compute and return”, events will only get in the way.

5. Common mistakes

Mistake #1: confusing an event with a command.
When you name an event sendEmail, the architecture starts “asking” the event source to know what exactly should happen. That breaks loose coupling: the source starts depending on specific actions again. If you want events — name them as facts (userRegistered, expenseAdded) and keep in mind the idea “an event must be true”.

Mistake #2: making a “central function” that still knows all reactions.
Sometimes a developer says: “OK, we’ll have an event”, but then writes emitExpenseAdded that manually calls audit(), recalcStats(), saveToFile() inside. That’s just moving the same coupling to a different place. The event-driven model is useful exactly when reactions are connected from the outside and the source doesn’t know who they are.

Mistake #3: not agreeing on the contract for error behavior.
If one handler throws an exception and you didn’t account for it, the result will be “random”: sometimes everything ran, sometimes the program crashed, sometimes some reactions didn’t happen. Even in a learning project it’s worth deciding in advance: “if one fails — we still call the others” or “the error is critical — we abort everything”. In the next lectures we’ll make dispatch resilient, but the idea should appear already now.

Mistake #4: building logic where listener order is critical, but it’s not documented anywhere.
If you silently expect that “stats first, then saving”, and someone changes the subscription order, you get a bug that’s impossible to understand from the code of addExpense. If order is truly important, it must become part of the contract (and then it’s closer to a conveyor/pipeline than to “free reactions”).

Mistake #5: trying to replace absolutely all function calls with events.
Events are great for extensible “one → many” reactions, where listeners can appear and disappear. But if you need a simple result like “compute and return”, events will only get in the way. Good architecture is not “events everywhere”, but “events where they actually reduce coupling and make extension cheaper”.

1
Task
Kotlin SELF, level 57, lesson 0
Locked
Registration as a fact
Registration as a fact
1
Task
Kotlin SELF, level 57, lesson 0
Locked
Level change
Level change
1
Task
Kotlin SELF, level 57, lesson 0
Locked
Creating an order
Creating an order
1
Task
Kotlin SELF, level 57, lesson 0
Locked
Cart events
Cart events
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION