CodeBlanks Logo Icon CodeBlanks

SharedFlow

Learn shared streams with SharedFlow.

What is SharedFlow?

SharedFlow is a hot flow that broadcasts to multiple collectors at once. Unlike StateFlow it has no initial value; it only delivers values that are emitted.

It is created with MutableSharedFlow<T>(); you push values with .emit(value). New collectors only receive later emissions. It fits event driven notifications: a button click, an alert when a message arrives. The replay parameter can deliver the last N values to new collectors.

Using SharedFlow

You open a MutableSharedFlow and listen with .collect inside a launch. When another coroutine calls .emit, the collector receives the value.

Example: val flow = MutableSharedFlow<Int>(). Inside a launch you open flow.collect { v -> println(v) }; in the main flow flow.emit(1) delivers 1 to the collector. A second collect open at the same time also receives each value.

Practice Emit and collect with SharedFlow

Define val flow = MutableSharedFlow<Int>(). Inside a launch, open flow.collect { value -> println("Got: $value") }. After delay(100) call flow.emit(1), wait delay(100) and stop the collector with job.cancel().

Starter code

Main.kt
// SharedFlow emit and collect
// write here
fun main() = runBlocking {
    
}

Sample solution

Main.kt
fun main() = runBlocking {
    val flow = MutableSharedFlow<Int>()
    val job = launch {
        flow.collect { value -> println("Got: $value") }
    }
    delay(100)
    flow.emit(1)
    delay(100)
    job.cancel()
}

Expected output

Got: 1

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Match SharedFlow parts

Term Meaning
MutableSharedFlow Broadcast holder
.emit Sends a value
.collect Collecting
replay Last N values

2 Does SharedFlow have an initial value?

  • Yes, always
  • Only with suspend
  • Only for Int
  • No, it does not Correct answer

Explanation: SharedFlow has no initial value.

3 Complete the SharedFlow type parameter

Question
val flow = MutableSharedFlow<____>()
Answer
val flow = MutableSharedFlow<Int>()

Explanation: SharedFlow needs a type parameter.

All lessons in Advanced