0
0
Kotlinprogramming~3 mins

Why SharedFlow for event broadcasting in Kotlin? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could send one message and have everyone hear it instantly without extra work?

The Scenario

Imagine you have a group chat where you want to share a message with everyone instantly. Doing this by sending individual texts to each person one by one is tiring and slow.

The Problem

Manually sending events to multiple listeners means writing repetitive code, risking missed messages, and struggling to keep everyone updated at the same time.

The Solution

SharedFlow acts like a broadcast channel where one message is sent once and all listeners receive it instantly, making event sharing smooth and reliable.

Before vs After
Before
fun sendEventToListeners(event: String, listeners: List<(String) -> Unit>) {
    for (listener in listeners) {
        listener(event)
    }
}
After
val sharedFlow = MutableSharedFlow<String>()
suspend fun broadcastEvent(event: String) {
    sharedFlow.emit(event)
}
// Collecting from sharedFlow should be done in a coroutine
// Example:
// CoroutineScope(Dispatchers.Main).launch {
//     sharedFlow.collect { event -> println("Received: $event") }
// }
What It Enables

It enables efficient, real-time event broadcasting to many receivers without complex manual handling.

Real Life Example

In a chat app, when one user sends a message, SharedFlow broadcasts it instantly to all active users without delay or missed updates.

Key Takeaways

Manual event sending is slow and error-prone.

SharedFlow broadcasts events to many listeners efficiently.

This makes real-time communication smooth and reliable.