0
0
Kotlinprogramming~5 mins

SharedFlow for event broadcasting in Kotlin

Choose your learning style9 modes available
Introduction

SharedFlow lets many parts of your app listen to the same events at the same time. It helps send messages that everyone can hear.

You want to send a message to many listeners at once, like a chat message.
You need to broadcast updates, such as a new notification, to multiple screens.
You want to share user actions, like button clicks, with different parts of your app.
You want to handle events that happen only once but need to be seen by many.
You want to avoid missing events even if some listeners start late.
Syntax
Kotlin
val sharedFlow = MutableSharedFlow<Type>(replay = 0)

// To send an event
sharedFlow.emit(value)

// To listen for events
sharedFlow.collect { value ->
    // handle value
}

MutableSharedFlow is used to create a flow you can send events to.

The replay parameter controls how many past events new listeners get.

Examples
This example creates a SharedFlow of strings with no replay. Listeners get only new events.
Kotlin
val sharedFlow = MutableSharedFlow<String>(replay = 0)

// Emit an event
sharedFlow.emit("Hello")

// Collect events
sharedFlow.collect { message ->
    println("Received: $message")
}
Here, replay is 2, so new listeners get the last two events immediately.
Kotlin
val sharedFlow = MutableSharedFlow<Int>(replay = 2)

// Emit some numbers
sharedFlow.emit(1)
sharedFlow.emit(2)
sharedFlow.emit(3)

// New collector will receive last 2 events: 2 and 3
Sample Program

This program shows two listeners receiving events from a SharedFlow. The second listener starts after some events were emitted but still receives the last event because replay is 1.

Kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val sharedFlow = MutableSharedFlow<String>(replay = 1)

    // First listener
    launch {
        sharedFlow.collect { value ->
            println("Listener 1 received: $value")
        }
    }

    // Emit events
    sharedFlow.emit("Event 1")
    sharedFlow.emit("Event 2")

    delay(100) // Wait a bit

    // Second listener starts late
    launch {
        sharedFlow.collect { value ->
            println("Listener 2 received: $value")
        }
    }

    sharedFlow.emit("Event 3")

    delay(100) // Wait to see output
}
OutputSuccess
Important Notes

SharedFlow is hot, meaning it keeps running even if no one listens.

Use replay carefully to avoid memory issues with many events.

Collecting from SharedFlow should be done in a coroutine.

Summary

SharedFlow lets you send events to many listeners at once.

Listeners can get past events if replay is set.

It is useful for broadcasting messages or user actions in apps.