1. Publishing and subscribing in SharedFlow
If you just wrote a neat Event<T> with a snapshot and an unsubscribe token, a logical question sounds like this: “Why do I need some SharedFlow as well? I just defeated chaos.” And that’s a fair question: your own Event<T> really is fine for synchronous broadcasting within regular code.
But as soon as we enter the world of coroutines, a new lifestyle appears: subscribers become coroutines, the subscription “lifecycle” is more convenient to control through Job, and broadcasting events naturally fits the data stream model (Flow). In Kotlin there are several ways to exchange data between coroutines, and SharedFlow is described as a mechanism that “shares each value with all active collectors.”
The point of this lecture: learn to use SharedFlow as an “event bus” in coroutine code, understand how subscription and “unsubscription” work, and why the replay parameter makes tutorial examples stable and independent of “did/didn’t make it in time.”
MutableSharedFlow and SharedFlow: “remote control” and “screen”
When you first see MutableSharedFlow<T>, you might want to hand it to everyone: “let whoever wants emit.” This is like leaving the “launch rocket” button on the kitchen table next to the cookies. Formally convenient, but then you spend half the day figuring out who and why “fired” an extra event.
In the coroutine world it’s common to split roles: MutableSharedFlow<T> is the publishing point (events get “pushed” there), and SharedFlow<T> is the safe “read-only” view (events are only read from it via collect). This approach aligns well with the general idea of separating responsibilities and reducing coupling: we expose subscription outward, but we don’t expose the ability to publish from anywhere.
Let’s build a minimal “event bus” for our console app (say it’s a small CLI task tracker with add/remove commands, and events are needed for audit and notifications).
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
sealed interface AppEvent
data class TaskAdded(val text: String) : AppEvent
class EventBus {
private val _events = MutableSharedFlow<AppEvent>(replay = 1)
val events: SharedFlow<AppEvent> = _events.asSharedFlow()
suspend fun emit(event: AppEvent) = _events.emit(event)
}
Notice two things. First, _events is private and “mutable” (you can change it, you can emit into it). Second, what’s exposed publicly is events: SharedFlow<AppEvent>—subscribe as much as you want, but you cannot “publish” directly.
Subscribing via collect: the “listener” lives in a coroutine
In our homemade event system, a listener was a regular function (T) -> Unit that we stored in a list. With SharedFlow, a listener turns into a collector coroutine: you start launch { flow.collect { ... } }, and while that coroutine is alive, it receives events.
This is very convenient for lifecycle management: “unsubscribing” is simply canceling the Job. No searching for “that exact lambda,” no remove(listener). A subscription lives exactly as long as the coroutine lives, which matches the idea of structured concurrency: child tasks live inside a parent scope.
Minimal example: “two subscribers receive all events”:
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect
fun main() = runBlocking {
val bus = EventBus()
val a = launch {
bus.events.collect { println("A got: $it") }
}
val b = launch {
bus.events.collect { println("B got: $it") }
}
bus.emit(TaskAdded("Buy milk")) // A got: TaskAdded(text=Buy milk), B got: TaskAdded(text=Buy milk)
a.cancel() // unsubscribed
b.cancel() // unsubscribed
}
The key idea here: collect is a “subscription” that usually does not finish by itself. If you don’t cancel the job, the collector will wait for new events. For an “event bus” that’s normal: events are potentially infinite.
“Unsubscribing” in SharedFlow: cancel the Job, don’t search for a lambda
In the lecture about unsubscribe tokens we emphasized the “reference nature of lambdas”: you can unsubscribe only with the same reference. With SharedFlow, this layer of problems almost disappears because a subscription is not an “item in a list,” but a running coroutine.
So the practical unsubscribe recipe looks like this: keep the Job returned by launch, then call cancel() (sometimes also join(), but today canceling is enough). It’s also nice because coroutine cancellation is a familiar tool you already know from earlier days about structured concurrency.
Super-short example: “subscribed — got one event — unsubscribed”:
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect
fun main() = runBlocking {
val bus = EventBus()
val job = launch {
bus.events.collect { println("Audit: $it") }
}
bus.emit(TaskAdded("Read Kotlin docs")) // Audit: TaskAdded(text=Read Kotlin docs)
job.cancel() // subscription stopped
}
If you need a “temporary listener” (for example, “log only while a scenario is running”), Job.cancel() is exactly what the doctor ordered.
3. replay and “late” subscribers
The most common tutorial pain with event streams sounds like this: “I did emit, but the subscriber didn’t get anything. Did Kotlin break?” In reality, no: you accidentally demonstrated the classic late-subscriber scenario—a subscriber started listening after the event had already flown by.
By definition, a regular Flow produces values only when it’s collected (collect), and SharedFlow distributes values to all active collectors. But if there were no collectors at the time of the event, then for a SharedFlow with replay = 0 that event is, essentially, “not needed by anyone,” and it is not saved.
That’s why the replay parameter is so useful specifically in tutorial examples: it allows you to keep the last N events and “replay” them to new subscribers. In this lecture we use replay = 1 so that a new subscriber is guaranteed to see at least the “latest fact,” and the example doesn’t depend on timing.
Let’s look at two behaviors: first, (mentally) imagine replay = 0, then replay = 1. We’ll keep our EventBus with replay = 1, but we’ll show why it matters.
Late subscription: event first, subscriber later
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect
fun main() = runBlocking {
val bus = EventBus()
bus.emit(TaskAdded("EARLY")) // no subscribers, but replay=1 will remember the latest
val job = launch {
bus.events.collect { println("Late got: $it") }
}
// Thanks to replay=1, the subscriber will immediately receive "EARLY"
job.cancel()
}
If replay were 0, the line Late got: ... might not appear at all, and the student (and sometimes the instructor) would start suspecting a conspiracy between the timer and the scheduler.
What replay = 1 does in human terms
You can think of replay = 1 as an “airbag for the last event.” This doesn’t turn events into “state” (we won’t go deep into that topic), but for demos and simple scenarios where “the latest fact matters,” it makes behavior predictable: the subscriber connects and immediately sees the latest.
It’s important to agree with yourself on what you’re building: “pure events” with no memory, or “events where the latest value is important to show to a new observer.” In tutorial code, the second is often more beneficial because it’s more robust to coroutine start order.
4. Errors in collect handlers and “dying” subscriptions
When you wrote your own Event<T>, we wrapped each handler in try/catch so that one listener crashing wouldn’t break broadcasting for everyone. In SharedFlow a similar problem shows up differently: if inside collect { ... } you throw an exception and don’t catch it, the collector coroutine will complete. And if the coroutine completed, the subscription is over.
So “one error in a handler” can turn into “the subscriber silently died and will never listen again.” This is especially unpleasant because externally it looks like “events stopped arriving.”
Therefore, if a handler can crash, it makes sense to isolate errors right inside collect:
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect
fun main() = runBlocking {
val bus = EventBus()
val job = launch {
bus.events.collect { e ->
try {
if (e is TaskAdded && e.text == "BAD") error("broken handler")
println("OK: $e")
} catch (ex: Exception) {
println("handler error: ${ex.message}") // handler error: broken handler
}
}
}
bus.emit(TaskAdded("GOOD")) // OK: TaskAdded(text=GOOD)
bus.emit(TaskAdded("BAD")) // handler error: broken handler
bus.emit(TaskAdded("GOOD2"))// OK: TaskAdded(text=GOOD2)
job.cancel()
}
There’s a nice effect here: the subscription doesn’t die because of one problematic event. You’re essentially repeating the idea of “isolating handler errors,” but in a coroutine style.
5. Example: “commands → events → reactions”
So that SharedFlow doesn’t look like “magic for the sake of magic,” let’s embed it into an understandable everyday scenario. Suppose we have a task list (MutableList<String>) and an add command. Inside the command we want to: add a task and publish an event. Separate subscribers will perform audit logging and show a notification to the user.
The process diagram might look like this:
flowchart LR
CLI[Komanda v CLI] --> Domain[Logika add/remove]
Domain --> Bus[EventBus / SharedFlow]
Bus --> Audit[Audit subscriber]
Bus --> Ui[UI subscriber]
Domain functions publish an event and don’t know about subscribers
import kotlinx.coroutines.runBlocking
fun addTask(tasks: MutableList<String>, text: String, bus: EventBus) = runBlocking {
tasks += text
bus.emit(TaskAdded(text))
}
Yes, runBlocking looks a bit rough here (and in a real app you would do this more cleanly), but for a tutorial console example the idea is simple: an action happened—an event was published. The event source doesn’t know who is listening.
Subscribers connect in main and live as long as the app lives
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.flow.collect
fun main() = runBlocking {
val tasks = mutableListOf<String>()
val bus = EventBus()
val auditJob = launch {
bus.events.collect { println("AUDIT: $it") }
}
val uiJob = launch {
bus.events.collect { println("UI: task list changed") }
}
addTask(tasks, "Learn SharedFlow", bus)
// AUDIT: TaskAdded(text=Learn SharedFlow)
// UI: task list changed
auditJob.cancel()
uiJob.cancel()
}
A funny (and realistic) moment: a UI subscriber in the console is just println. But architecturally it’s the same technique as in large applications: the same fact “task added” can interest different parts of the system.
6. Event<T> vs SharedFlow: when to choose what
Sometimes the right conclusion from this topic is not “SharedFlow is better,” but rather “these are different tools for different situations.” A homemade Event<T> is great for simple synchronous broadcasting where you want full control and minimal dependencies. SharedFlow is convenient when you already live in coroutines and want subscribe/unsubscribe via Job and a unified style with Flow.
Let’s compare in a table (without diving into fine-grained settings):
| Criterion | (homemade) |
|
|---|---|---|
| Subscription model | list of functions (T) -> Unit | coroutine + collect { ... } |
| Unsubscribe | token, remove listener | |
| Listener error | catch try/catch around the call | if not caught, the collector coroutine will complete |
| Keeping the “last event” | must be implemented manually | replay = 1 (and more) |
| Relationship with coroutines | not required | native environment |
If somewhere it’s simpler for you to use a “regular list of listeners”—use Event<T>. If you’re already in coroutine code and want the stream model—use SharedFlow. Kotlin is good precisely because it doesn’t force you to choose one style forever.
7. Common mistakes when using SharedFlow as an event bus
Mistake No. 1: making MutableSharedFlow public.
When what you expose is MutableSharedFlow itself, any piece of code can start emitting events. As a result, events stop being “truth from the source” and become “anything goes.” It’s much more robust to keep MutableSharedFlow private and expose SharedFlow so external parts can only subscribe.
Mistake No. 2: forgetting that collect usually doesn’t finish on its own.
A beginner often writes launch { flow.collect { ... } } and expects the coroutine to “finish” after one event. But collect is a subscription, and it will keep waiting. If you don’t cancel the Job, the subscriber will remain active. This is not a bug: it’s the contract. Just keep the lifecycle in mind.
Mistake No. 3: expecting past events when replay = 0.
If replay is 0, late subscribers are not required to receive past events—they will only see future ones. For tutorial examples and demos, it’s better to set replay = 1; otherwise you become dependent on timing: whoever starts first wins.
Mistake No. 4: not catching exceptions inside the collect handler.
If a handler inside collect throws, the collector coroutine may complete, and the subscription will “die.” Then you’ll spend a long time wondering why events stopped arriving. If the handler is potentially fragile, isolate errors with try/catch right inside collect, like we did earlier for individual listeners in Event<T>.
Mistake No. 5: confusing “events” with “state” and setting replay without understanding.
replay = 1 makes behavior more stable, but it’s already “a bit of memory.” If you mindlessly increase replay or start relying on it as “storage,” you can easily get odd effects: a new subscriber sees old events and reacts as if they just happened. In this lecture, replay = 1 is a deliberate tutorial setting, not a universal recommendation for all cases.
Mistake No. 6: thinking SharedFlow automatically makes handlers safe from reentrancy.
In the manual event implementation we solved “modifying the listener list during broadcast” using a snapshot (toList()), and it worked because we controlled the data structure. With SharedFlow you have a different model: handlers live in coroutines, and it’s important to watch what they do inside. If a handler reacts to an event by publishing new events, you can get a cascade. That’s not necessarily bad, but it should be a conscious design, not an accidental reaction like “oh, let’s emit here as well.”
GO TO FULL VERSION