Intermediate 8 min readKotlin 2.0

Kotlin SharedFlow โ€” Events and Broadcast Streams

SharedFlow is a hot flow for broadcasting values to multiple collectors. Use it for one-time UI events; use StateFlow for state.

What You Will Learn

  • Create MutableSharedFlow
  • Emit events with emit()
  • Configure replay and buffer
  • Compare SharedFlow vs StateFlow
  • Model one-time UI events safely

SharedFlow Basics

Unlike cold flow { }, SharedFlow is hot โ€” active collectors share the same stream. replay=0 is typical for one-time events.

Emit and Collect

kotlin
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*

fun main() = runBlocking {
    val events = MutableSharedFlow<String>()
    val job = launch {
        events.collect { println("Event: $it") }
    }
    delay(50)
    events.emit("Signed in")
    events.emit("Profile updated")
    delay(50)
    job.cancel()
}
Output
Event: Signed in Event: Profile updated

emit() sends events to active collectors. Late subscribers do not receive past events when replay is 0.

Dependency required: implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")

SharedFlow vs StateFlow

StateFlow always has a current value and replays the latest to new collectors. SharedFlow is better for navigation events, snackbars, and taps.

When to Use Which

kotlin
// StateFlow โ€” UI state (always has current value)
// val uiState = MutableStateFlow(UiState())

// SharedFlow โ€” one-time events (no initial value required)
// val snackbarEvents = MutableSharedFlow<String>()
Output
No console output

This snippet shows the intent: StateFlow for state, SharedFlow for events that should not be replayed to new subscribers.

Best Practice: On Android, expose StateFlow for UI state and SharedFlow for one-off events like navigation.

Practice Exercise

Exercisemultiple choice

Which flow is best for a one-time "navigate to settings" event?

Quick Quiz

Quick Quiz

What makes SharedFlow "hot"?

Frequently Asked Questions

Related Tutorials

Last updated: 2026-05-19Kotlin 2.0

Written by KotlinGuide Editorial Team ยท Reviewed by KotlinGuide Technical Review