0
0
Kotlinprogramming~5 mins

SharedFlow for event broadcasting in Kotlin - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: SharedFlow for event broadcasting
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

When you send one event, the work grows with how many listeners are subscribed.

Number of Subscribers (n)Approx. Notifications
1010 notifications
100100 notifications
10001000 notifications

Pattern observation: The work grows directly with the number of subscribers.

Final Time Complexity

Time Complexity: O(n)

This means sending one event takes time proportional to how many listeners are subscribed.

Common Mistake

[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.

Interview Connect

Understanding how event broadcasting scales helps you design responsive apps and explain performance in real projects.

Self-Check

"What if we buffer events in SharedFlow? How would that affect the time complexity of emitting events?"