SharedFlow for event broadcasting in Kotlin - Time & Space Complexity
We want to understand how the time cost changes when using SharedFlow to send events to many listeners.
How does the number of listeners affect the work done when broadcasting an event?
Analyze the time complexity of the following code snippet.
val sharedFlow = MutableSharedFlow()
suspend fun broadcastEvent(event: String) {
sharedFlow.emit(event) // send event to all subscribers
}
fun subscribe() {
sharedFlow.onEach { event ->
println("Received: $event")
}.launchIn(scope)
}
This code sends an event to all subscribers using SharedFlow, which broadcasts to multiple listeners.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Emitting an event triggers notifying each subscriber.
- How many times: Once per subscriber, so the number of subscribers determines repetitions.
When you send one event, the work grows with how many listeners are subscribed.
| Number of Subscribers (n) | Approx. Notifications |
|---|---|
| 10 | 10 notifications |
| 100 | 100 notifications |
| 1000 | 1000 notifications |
Pattern observation: The work grows directly with the number of subscribers.
Time Complexity: O(n)
This means sending one event takes time proportional to how many listeners are subscribed.
[X] Wrong: "Emitting an event is always fast and does not depend on subscribers."
[OK] Correct: Each subscriber must receive the event, so more subscribers mean more work.
Understanding how event broadcasting scales helps you design responsive apps and explain performance in real projects.
"What if we buffer events in SharedFlow? How would that affect the time complexity of emitting events?"