Complete the code to declare a MutableSharedFlow for events.
val eventFlow = MutableSharedFlow<[1]>()The MutableSharedFlow is declared with the type of events it will emit. Here, String is used for simple text events.
Complete the code to emit an event string into the SharedFlow.
viewModelScope.launch {
eventFlow.[1]("ButtonClicked")
}collect which is for receiving, not sending.send which is for Channels, not SharedFlow.To send an event to the SharedFlow, use the emit function inside a coroutine.
Fix the error in collecting events from the SharedFlow in a lifecycle-aware way.
lifecycleScope.launchWhenStarted {
eventFlow.[1] { event ->
handleEvent(event)
}
}emit which is for sending events.subscribe which is not a Kotlin Flow function.To receive events from a SharedFlow, use the collect function inside a coroutine.
Fill both blanks to create a SharedFlow that replays the last event and has no extra buffer.
val eventFlow = MutableSharedFlow<String>(replay = [1], extraBufferCapacity = [2])
Setting replay = 1 makes the flow replay the last event to new subscribers. extraBufferCapacity = 0 means no extra buffering.
Fill all three blanks to collect events from SharedFlow in a Compose UI using LaunchedEffect.
LaunchedEffect(Unit) {
eventFlow.[1] { event ->
when(event) {
[2] -> showToast("Clicked")
[3] -> showToast("Error")
}
}
}emit instead of collect to receive events.Use collect to receive events. Match event strings to show appropriate messages.