Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a mutable state variable in ViewModel.
Android Kotlin
private val _count = MutableStateFlow([1])
val count: StateFlow<Int> = _count Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using empty string "" instead of 0 for an integer state.
Using null which is not allowed without nullable type.
Using false which is a Boolean, not an Int.
✗ Incorrect
We initialize the mutable state with 0 because count is an integer.
2fill in blank
mediumComplete the code to update the state value inside ViewModel.
Android Kotlin
fun increment() {
_count.value = _count.value [1] 1
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' which is not valid for StateFlow value assignment.
Using '-' or '*' which change the value incorrectly.
✗ Incorrect
We add 1 to the current value to increment the count.
3fill in blank
hardFix the error in the ViewModel state declaration.
Android Kotlin
class CounterViewModel : ViewModel() { private val _count = MutableStateFlow<Int>([1]) val count: StateFlow<Int> = _count }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using null which causes a runtime error.
Using string "0" which is not an Int.
Using false which is a Boolean.
✗ Incorrect
MutableStateFlow requires a non-null initial value matching the type Int, so 0 is correct.
4fill in blank
hardFill both blanks to create a function that resets the count to zero.
Android Kotlin
fun reset() {
_count.[1] = [2]
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'emit' which is a suspend function and cannot be called directly here.
Assigning null which is not allowed for non-nullable Int state.
✗ Incorrect
We assign 0 to the value property of _count to reset the state.
5fill in blank
hardFill all three blanks to create a ViewModel with a mutable state and a function to decrement the count.
Android Kotlin
class CounterViewModel : ViewModel() { private val _count = MutableStateFlow([1]) val count: StateFlow<Int> = [2] fun decrement() { _count.value = _count.value [3] 1 } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Exposing 'count' instead of '_count' for the public state.
Using '+' instead of '-' for decrement.
Initializing with a wrong type.
✗ Incorrect
The state starts at 0, the public state is _count, and decrement subtracts 1.