0
0
Android Kotlinmobile~10 mins

State in ViewModel in Android Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
Afalse
B""
C0
Dnull
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.
2fill in blank
medium

Complete 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'
A+
B-
C+=
D*
Attempts:
3 left
💡 Hint
Common Mistakes
Using '+=' which is not valid for StateFlow value assignment.
Using '-' or '*' which change the value incorrectly.
3fill in blank
hard

Fix 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'
Anull
Bfalse
C"0"
D0
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.
4fill in blank
hard

Fill 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'
Avalue
B0
Cnull
Demit
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.
5fill in blank
hard

Fill 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'
A0
B_count
C-
Dcount
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.