0
0
Kotlinprogramming~10 mins

StateFlow for observable state in 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 create a MutableStateFlow with initial value 0.

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

Complete the code to update the StateFlow value by incrementing it by 1.

Kotlin
counter.value = counter.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 decreases the value
Using '*' or '/' which changes the value differently
3fill in blank
hard

Fix the error in the code to collect StateFlow values in a coroutine.

Kotlin
lifecycleScope.launch {
    counter.[1] { value ->
        println("Counter: $value")
    }
}
Drag options to blanks, or click blank then click option'
Aemit
Bcollect
CcollectLatest
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using emit instead of collect
Using value which is not a function
Using collectLatest which is valid but not the simplest here
4fill in blank
hard

Fill both blanks to create a StateFlow that only emits even numbers from a MutableStateFlow.

Kotlin
val evenNumbers = counter.[1] { it % 2 == 0 }.[2]()
Drag options to blanks, or click blank then click option'
Afilter
Bmap
CstateIn
Dcollect
Attempts:
3 left
💡 Hint
Common Mistakes
Using map instead of filter
Using collect which is for terminal operations
Not converting back to StateFlow with stateIn
5fill in blank
hard

Fill all three blanks to create a StateFlow with initial value 0, update it, and collect its values.

Kotlin
val counter = MutableStateFlow([1])

counter.value = counter.value [2] 5

lifecycleScope.launch {
    counter.[3] { value ->
        println("Value: $value")
    }
}
Drag options to blanks, or click blank then click option'
A0
B+
Ccollect
D-
Attempts:
3 left
💡 Hint
Common Mistakes
Using '-' instead of '+' for updating
Using emit instead of collect
Using wrong initial value