SharedFlow

Broadcasting Events

SharedFlow<T> is a hot flow that broadcasts every emitted value to all current collectors. It has no "current value". Configure it with:

ParameterMeaning
replayhow many past values a new collector receives (default 0)
extraBufferCapacityextra buffer so emit does not suspend for slow collectors
onBufferOverflowSUSPEND (default), DROP_OLDEST, DROP_LATEST

Example

Example

Two collectors get every event. A collector that subscribes late gets only the replayed values.

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

fun main() = runBlocking {
    val events = MutableSharedFlow<String>()               // replay = 0
    val a = launch { events.collect { println("Toast:     $it") } }
    val b = launch { events.collect { println("Analytics: $it") } }
    delay(10)
    events.emit("Payment successful")
    events.emit("Coupon applied")
    delay(10)
    a.cancel(); b.cancel()

    val news = MutableSharedFlow<String>(replay = 2)
    news.emit("Sensex up 300")
    news.emit("Rupee steady")
    news.emit("Gold at record high")
    val late = launch { news.collect { println("Late subscriber got: $it") } }
    delay(10)
    late.cancel()
}

Output

Toast:     Payment successful
Analytics: Payment successful
Toast:     Coupon applied
Analytics: Coupon applied
Late subscriber got: Rupee steady
Late subscriber got: Gold at record high

tryEmit

emit is a suspend function. From non-suspending code (a click listener) use tryEmit, which needs buffer space:

private val _events = MutableSharedFlow<UiEvent>(extraBufferCapacity = 1)
val events: SharedFlow<UiEvent> = _events.asSharedFlow()

fun onShareClicked() {
    _events.tryEmit(UiEvent.OpenShareSheet)   // returns false if the buffer is full
}