Consider this Kotlin code using MutableSharedFlow to broadcast events. What will be printed?
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val sharedFlow = MutableSharedFlow<Int>() launch { sharedFlow.collect { value -> println("Collector 1 received: $value") } } launch { delay(100) sharedFlow.emit(1) sharedFlow.emit(2) } launch { delay(200) sharedFlow.collect { value -> println("Collector 2 received: $value") } } delay(500) }
Think about when Collector 2 starts collecting and what events it can receive.
Collector 1 starts immediately and receives both emitted values 1 and 2. Collector 2 starts collecting after a delay of 200ms, after both emissions around 100ms, so with replay=0 and no extra buffer, it receives nothing.
In MutableSharedFlow(replay = 1), what does the replay parameter do?
Think about what replay means in the context of event streams.
The replay parameter controls how many past events are stored and sent to new collectors immediately upon subscription. Setting it to 1 means the last event is replayed to new subscribers.
Examine this Kotlin code snippet. Why does it cause the program to hang indefinitely?
import kotlinx.coroutines.* import kotlinx.coroutines.flow.* fun main() = runBlocking { val sharedFlow = MutableSharedFlow<Int>(replay = 0, extraBufferCapacity = 0) launch { sharedFlow.emit(1) println("Emitted 1") } delay(100) sharedFlow.collect { value -> println("Collected: $value") } }
Think about how emit behaves when there are no active collectors and no buffer.
With replay=0 and extraBufferCapacity=0, emit suspends until a collector is ready to receive the value. Since emit is called before collect, it waits forever, causing a deadlock.
Choose the correct Kotlin code to create a MutableSharedFlow with replay = 2 and extraBufferCapacity = 3.
Check the official parameter names for MutableSharedFlow constructor.
The correct parameter names are replay and extraBufferCapacity. Options A and B use wrong parameter names, and D swaps the values.
You want to broadcast events so that every collector receives all emitted events, even if they start collecting late. Which SharedFlow configuration achieves this?
Think about how replay buffers past events for new collectors.
Setting replay to a very large number buffers all emitted events so new collectors receive all past events. Other options either buffer nothing or rely on timing, which is unreliable.