Complete the code to declare a MutableStateFlow with initial value 0.
val counter = MutableStateFlow([1])The MutableStateFlow must be initialized with a starting value. Here, 0 is the correct integer initial value.
Complete the code to expose the StateFlow as a read-only flow from MutableStateFlow.
val _counter = MutableStateFlow(0) val counter: StateFlow<Int> = _counter.[1]
Use asStateFlow() to expose a read-only StateFlow from a MutableStateFlow.
Fix the error in updating the MutableStateFlow value inside a function.
fun increment() {
_counter.[1] = _counter.value + 1
}To update the value of a MutableStateFlow, assign the new value to its value property.
Fill both blanks to collect the StateFlow in a lifecycle-aware way inside a Fragment.
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
counter.[1] { value ->
textView.text = value.toString()
}
}Use collect to observe StateFlow emissions inside a coroutine.
Fill both blanks to create a StateFlow that holds a list of strings and add a new item.
private val _items = MutableStateFlow<List<String>>([1]) val items: StateFlow<List<String>> = _items.asStateFlow() fun addItem(newItem: String) { _items.value = _items.value [2] listOf(newItem) }
Initialize with an empty list using emptyList(). Use plus to add an item to the list immutably.