0
0
Android Kotlinmobile~10 mins

StateFlow for reactive state 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 MutableStateFlow with initial value 0.

Android Kotlin
val counter = MutableStateFlow([1])
Drag options to blanks, or click blank then click option'
Afalse
B"0"
Cnull
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using a string "0" instead of integer 0
Leaving the initial value null
Using a boolean false instead of a number
2fill in blank
medium

Complete the code to expose the StateFlow as a read-only flow from MutableStateFlow.

Android Kotlin
val _counter = MutableStateFlow(0)
val counter: StateFlow<Int> = _counter.[1]
Drag options to blanks, or click blank then click option'
AtoFlow()
BtoStateFlow()
CasStateFlow()
Dstate()
Attempts:
3 left
💡 Hint
Common Mistakes
Using a non-existent function like toStateFlow()
Trying to assign MutableStateFlow directly without conversion
Using toFlow() which returns a Flow, not StateFlow
3fill in blank
hard

Fix the error in updating the MutableStateFlow value inside a function.

Android Kotlin
fun increment() {
  _counter.[1] = _counter.value + 1
}
Drag options to blanks, or click blank then click option'
Avalue
BsetValue
Cemit
Dupdate
Attempts:
3 left
💡 Hint
Common Mistakes
Using emit which is a suspend function and not available on MutableStateFlow
Trying to call setValue which does not exist
Using update which is an extension function but not a property
4fill in blank
hard

Fill both blanks to collect the StateFlow in a lifecycle-aware way inside a Fragment.

Android Kotlin
viewLifecycleOwner.lifecycleScope.launchWhenStarted {
  counter.[1] { value ->
    textView.text = value.toString()
  }
}
Drag options to blanks, or click blank then click option'
Acollect
BcollectLatest
Claunch
Dobserve
Attempts:
3 left
💡 Hint
Common Mistakes
Using collectLatest which cancels previous collector but not necessary here
Using launch which is for starting coroutines, not collecting flows
Using observe which is for LiveData, not StateFlow
5fill in blank
hard

Fill both blanks to create a StateFlow that holds a list of strings and add a new item.

Android Kotlin
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)
}
Drag options to blanks, or click blank then click option'
AemptyList()
B+
Cplus
DlistOf()
Attempts:
3 left
💡 Hint
Common Mistakes
Initializing with listOf() without elements
Using + operator which works but plus() is clearer for lists
Trying to modify the list directly instead of creating a new list