Complete the code to create a StateFlow with an initial value of 0.
val _counter = MutableStateFlow([1])
val counter: StateFlow<Int> = _counterStateFlow requires an initial value. Here, 0 is the correct integer initial value.
Complete the code to emit a new value 5 to a MutableSharedFlow.
val events = MutableSharedFlow<Int>()
suspend fun sendEvent() {
events.[1](5)
}To send a value to a SharedFlow, use the emit function inside a suspend function.
Fix the error in the code to collect values from a StateFlow named stateFlow inside a coroutine.
lifecycleScope.launch {
stateFlow.[1] { value ->
println(value)
}
}To receive values from a StateFlow, use the collect function inside a coroutine.
Fill both blanks to create a SharedFlow that replays the last 3 emitted values and has a buffer capacity of 5.
val sharedFlow = MutableSharedFlow<Int>(replay = [1], extraBufferCapacity = [2])
The replay parameter sets how many past values are replayed to new collectors. extraBufferCapacity sets the buffer size for emitted values.
Fill all three blanks to create a StateFlow that updates its value and exposes it as an immutable StateFlow.
private val _state = MutableStateFlow([1]) val state: StateFlow<Int> = _state.[2] fun updateValue(newValue: Int) { _state.[3] = newValue }
Initialize MutableStateFlow with 0. Use asStateFlow() to expose immutable StateFlow. Update value by setting value property.