0Pricing
Kotlin Academy · Lesson

SharedFlow: Event Buses and One-Shot Events

Configure SharedFlow replay and extraBufferCapacity for event broadcasting.

What Is SharedFlow?

SharedFlow is a hot Flow that broadcasts to all active collectors. Unlike StateFlow, it has no concept of a current value — it is purely event-driven.

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val events = MutableSharedFlow<String>()
    launch { events.collect { println("Collector 1: $it") } }
    launch { events.collect { println("Collector 2: $it") } }
    delay(50)
    events.emit("UserLoggedIn")
    events.emit("DataRefreshed")
    delay(50)
    coroutineContext.cancelChildren()
}

replay Parameter

replay buffers the last N emissions. New collectors immediately receive up to N past events. Default is 0 (no replay).

import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
fun main() = runBlocking {
    val flow = MutableSharedFlow<Int>(replay = 2)
    flow.emit(1); flow.emit(2); flow.emit(3)
    // Late subscriber gets last 2:
    flow.collect { print("$it ") }  // prints 2 3
}

All lessons in this course

  1. StateFlow: Hot State Holder for UI
  2. SharedFlow: Event Buses and One-Shot Events
  3. Converting Cold Flow to Hot with shareIn and stateIn
  4. Testing StateFlow and SharedFlow with Turbine
← Back to Kotlin Academy