0
0
Android Kotlinmobile~10 mins

StateFlow and SharedFlow 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 create a StateFlow with an initial value of 0.

Android Kotlin
val _counter = MutableStateFlow([1])
val counter: StateFlow<Int> = _counter
Drag options to blanks, or click blank then click option'
A-1
Bnull
C"0"
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using null as initial value causes errors.
Using a string "0" instead of integer 0.
2fill in blank
medium

Complete the code to emit a new value 5 to a MutableSharedFlow.

Android Kotlin
val events = MutableSharedFlow<Int>()
suspend fun sendEvent() {
  events.[1](5)
}
Drag options to blanks, or click blank then click option'
Asubscribe
Bcollect
Cemit
Dlaunch
Attempts:
3 left
💡 Hint
Common Mistakes
Using collect instead of emit.
Trying to call emit outside a suspend function.
3fill in blank
hard

Fix the error in the code to collect values from a StateFlow named stateFlow inside a coroutine.

Android Kotlin
lifecycleScope.launch {
  stateFlow.[1] { value ->
    println(value)
  }
}
Drag options to blanks, or click blank then click option'
Acollect
Bemit
Csend
Dsubscribe
Attempts:
3 left
💡 Hint
Common Mistakes
Using emit instead of collect.
Trying to collect outside a coroutine.
4fill in blank
hard

Fill both blanks to create a SharedFlow that replays the last 3 emitted values and has a buffer capacity of 5.

Android Kotlin
val sharedFlow = MutableSharedFlow<Int>(replay = [1], extraBufferCapacity = [2])
Drag options to blanks, or click blank then click option'
A3
B5
C0
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Confusing replay with buffer capacity.
Setting replay or buffer to zero when not intended.
5fill in blank
hard

Fill all three blanks to create a StateFlow that updates its value and exposes it as an immutable StateFlow.

Android Kotlin
private val _state = MutableStateFlow([1])
val state: StateFlow<Int> = _state.[2]

fun updateValue(newValue: Int) {
  _state.[3] = newValue
}
Drag options to blanks, or click blank then click option'
A0
BasStateFlow()
Cvalue
Demit
Attempts:
3 left
💡 Hint
Common Mistakes
Trying to emit on StateFlow instead of setting value.
Exposing MutableStateFlow directly without asStateFlow.